您的位置:首页 > 其它

LeetCode OJ:Balanced Binary Tree(平衡二叉树)

2015-10-19 10:02 531 查看
Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

就是去查看一棵树是不是平衡的,一开始对平衡二叉树的理解有错误,所以写错了 ,看了别人的解答之后更正过来了:

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
int dep;
checkBalance(root, dep);
}
bool checkBalance(TreeNode * root, int &dep)
{
if(root == NULL){
dep = 0;
return true;
}
int leftDep, rightDep;
bool isLeftBal = checkBalance(root->left, leftDep);
bool isRightBal = checkBalance(root->right, rightDep);

dep = max(leftDep, rightDep) + 1;
return isLeftBal && isRightBal && (abs(leftDep - rightDep) <= 1);
}
};


pS:感觉这个不应该easy的题目啊 想的时候头还挺疼的。。

用java的时候用上面的方法去做总是无法成功,所以换了一种方法,这个一开始没有想到,是看别人写的,代码如下所示:

/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
public class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null)
return true;
if(root.left == null && root.right == null)
return true;
if(Math.abs(getDep(root.left) - getDep(root.right)) > 1)
return false;
return isBalanced(root.left) && isBalanced(root.right);
}

public int getDep(TreeNode node){
if(node == null)
return 0;
else
return 1 + Math.max(getDep(node.left), getDep(node.right));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: