Created
February 26, 2013 23:00
-
-
Save zhoutuo/5043176 to your computer and use it in GitHub Desktop.
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.
This file contains hidden or 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) {} | |
* }; | |
*/ | |
class Solution { | |
public: | |
bool isBalanced(TreeNode *root) { | |
// Start typing your C/C++ solution below | |
// DO NOT write int main() function | |
if(root == NULL) { | |
return true; | |
} | |
if(getHeight(root) == -1) { | |
return false; | |
} else { | |
return true; | |
} | |
} | |
int getHeight(TreeNode* root) { | |
if(root == NULL) { | |
return 0; | |
} else { | |
int left = getHeight(root->left); | |
int right = getHeight(root->right); | |
if(left == -1 or right == -1) { | |
return -1; | |
} | |
if(abs(left - right) > 1) { | |
return -1; | |
} else { | |
return max(left, right) + 1; | |
} | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment