判斷二叉樹是否是平衡二叉樹(C++)
阿新 • • 發佈:2019-02-13
輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹。
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot==NULL)
return true;
int rightDepth=getDepth(pRoot->right);
int leftDepth=getDepth(pRoot->left);
if(rightDepth>leftDepth+1||leftDepth>rightDepth+1 )
return false;
else return IsBalanced_Solution(pRoot->left)&&IsBalanced_Solution(pRoot->right);
}
int getDepth(TreeNode* pRoot)
{
if(pRoot==NULL)
return 0;
int rightDepth=getDepth(pRoot->right);
int leftDepth=getDepth(pRoot->left );
return 1+(leftDepth>rightDepth?leftDepth:rightDepth);
}
};