您的位置:首页 > 编程语言 > C语言/C++

Balanced Binary Tree --Leetcode C++

2015-06-03 20:34 435 查看
递归

左子树是否为平衡二叉树

右子树是否为平衡二叉树

左右子树高度差是否大于1,大于1,返回false

否则判断左右子树

最简单的理解方法就是如下的思路:

class Solution {
public:
bool isBalanced(TreeNode* root) {
if(root==NULL){
return true;
}
int ldepth=depth(root->left);
int rdepth=depth(root->right);
if(abs(ldepth-rdepth)>1)return false;
else{
return isBalanced(root->left)&&isBalanced(root->right);
}
}
int depth(TreeNode *root){
if(root==NULL){
return 0;
}
int lleft=depth(root->left);
int trigth=depth(root->right);
return lleft>trigth ? lleft+1:trigth+1;

}
};


在上面的方法中,每一个节点都会计算节点左子树和右子树的高度,存在大量的重复计算

所以,采用自底向上的方式

class Solution2 {
public:
bool isBalanced(TreeNode* root) {
if(root==NULL){
return true;
}
int height=getheight(root);
if(height==-1){
return false;
}
return true;
}
int getheight(TreeNode *root){
if(root==NULL){
return 0;
}
int lleft=getheight(root->left);
int trigth=getheight(root->right);
if(lleft==-1||trigth==-1){
return -1;
}
if(abs(lleft-trigth)>1){
return -1;
}
return lleft>trigth? lleft+1:trigth+1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: