Skip to content

Commit

Permalink
update the problem "Balanced Binary Tree"
Browse files Browse the repository at this point in the history
  • Loading branch information
haoel committed Dec 30, 2014
1 parent 7268885 commit 843db5c
Showing 1 changed file with 42 additions and 12 deletions.
54 changes: 42 additions & 12 deletions src/balancedBinaryTree/balancedBinaryTree.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,21 +25,51 @@ class Solution {
public:
bool isBalanced(TreeNode *root) {
int height=0;
return isBalancedUtil(root,&height);
return isBalancedUtil(root, height);
}
bool isBalancedUtil(TreeNode* root,int *height){

bool isBalancedUtil(TreeNode* root, int& height){
if(root==NULL){
*height=0;
return 1;
height=0;
return true;
}
int lh=0,rh=0;
bool isLeft,isRight;
isLeft=isBalancedUtil(root->left,&lh);
isRight=isBalancedUtil(root->right,&rh);
*height=(lh>rh?lh:rh)+1;
if(abs(lh-rh)>1)
return 0;
return isLeft&&isRight;
int lh=0, rh=0;
bool isLeft = isBalancedUtil(root->left, lh);
bool isRight = isBalancedUtil(root->right, rh);
height = (lh > rh ? lh : rh) + 1;
return (abs(lh-rh)<=1 && isLeft && isRight);
}

};

//Notes:
// I think the above solution should be more efficent than the below,
// but for leetcode, the below solution needs 60ms, the above needs 88ms
class Solution {
public:
bool isBalanced(TreeNode *root) {
if (root==NULL) return true;

int left = treeDepth(root->left);
int right = treeDepth(root->right);

if (left-right>1 || left-right < -1) {
return false;
}
return isBalanced(root->left) && isBalanced(root->right);
}

int treeDepth(TreeNode *root) {
if (root==NULL){
return 0;
}

int left=1, right=1;

left += treeDepth(root->left);
right += treeDepth(root->right);

return left>right?left:right;
}

};

0 comments on commit 843db5c

Please sign in to comment.