Created
August 31, 2014 07:14
-
-
Save xiren-wang/4cdd1e10faa9d5d1eab9 to your computer and use it in GitHub Desktop.
balanced binary tree.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for binary tree | |
* struct TreeNode { | |
* int val; | |
* TreeNode *left; | |
* TreeNode *right; | |
* TreeNode(int x) : val(x), left(NULL), right(NULL) {} | |
* }; | |
* 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. | |
*/ | |
class Solution { | |
public: | |
bool isBalanced(TreeNode *root) { | |
if (!root) | |
return true; | |
//get heights of left and right trees (height==-1 if already not balanced) | |
// Note: this is needed to check "every node" has balanced subtree | |
// if abs(diff) <= 1, true | |
int leftH = getHeight(root->left); | |
int rightH = getHeight(root->right); | |
return leftH>=0 && rightH>=0 && abs(leftH - rightH) <= 1; | |
} | |
int getHeight(TreeNode *root) { | |
if (!root) | |
return 0; | |
int leftH = getHeight(root->left); | |
int rightH = getHeight(root->right); | |
if (leftH < 0 || rightH < 0 ) //already not balanced | |
return -1; | |
if (abs(leftH - rightH) > 1) | |
return -1; | |
return 1 + max(leftH, rightH); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment