0
点赞
收藏
分享

微信扫一扫

lintcode: Balanced Binary Tree


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);
}
};


​​​https://haozhou.gitbooks.io/leetcode-java/content/binarytree/binarytree-balanced.html​​


举报

相关推荐

0 条评论