您的位置:首页 > 其它

[leetcode][tree][dfs] Balanced Binary Tree

2015-05-21 13:02 260 查看
题目:

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 height;
return isBalancedCore(root, height);
}
private:
bool isBalancedCore(TreeNode* root, int &height){//如果该树不平衡,返回false;如果该树平衡,返回true并通过height返回该树的高度
if(NULL == root){//递归终止条件,此时必须给height赋0值
height = 0;
return true;
}
int leftHeight;//左子树的高度(后面函数调用过程中将赋值)
int rightHeight;//右子树的高度(后面函数调用过程中将赋值)
if(isBalancedCore(root->left, leftHeight) && isBalancedCore(root->right, rightHeight) && abs(leftHeight-rightHeight) <= 1){
height = 1+max(leftHeight, rightHeight);
return true;
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: