题目
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
思路:
本题可以利用后序遍历,优先考察子树的平衡性,当子树不平衡时,该二叉树一定不平衡。
代码1(476k, 3ms)
class Solution {
public:
int getdepth(TreeNode* root){
if(root==NULL)
return 0;
int left=getdepth(root->left);
if(left==-1)
return -1;
int right=getdepth(root->right);
if(right ==-1)
return -1;
if(left-right>1||left-right<-1)
return -1;
else
return left>right?left+1:right+1;
}
bool IsBalanced_Solution(TreeNode* pRoot) {
return getdepth(pRoot)!=-1;
}
};
代码(484k, 3ms)
class Solution {
public:
bool isBalanced=true;
int getdepth(TreeNode* root){
if(root==NULL)
return 0;
int left=getdepth(root->left);
int right=getdepth(root->right);
if(left-right>1||left-right<-1)
isBalanced=false;
return left>right?left+1:right+1;
}
bool IsBalanced_Solution(TreeNode* pRoot) {
getdepth(pRoot);
return isBalanced;
}
};