您的位置:首页 > 其它

lintcode: Balanced Binary Tree

2016-03-20 23:04 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 of TreeNode:
* class TreeNode {
* public:
*     int val;
*     TreeNode *left, *right;
*     TreeNode(int val) {
*         this->val = val;
*         this->left = this->right = NULL;
*     }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: True if this Binary tree is Balanced, or false.
*/
int height(TreeNode *node){
if(node==NULL){
return 0;
}
return max(height(node->left),height(node->right))+1;
}

bool isBalanced(TreeNode *root) {
// write your code here

if(root==NULL){
return true;
}

int diff=height(root->left)-height(root->right);
if(diff>1||diff<-1){
return false;
}

return isBalanced(root->left) && isBalanced(root->right);
}
};


参考:

/article/5767604.html

https://haozhou.gitbooks.io/leetcode-java/content/binarytree/binarytree-balanced.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: