Skip to content

Instantly share code, notes, and snippets.

@xiren-wang
Created August 31, 2014 07:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiren-wang/4cdd1e10faa9d5d1eab9 to your computer and use it in GitHub Desktop.
Save xiren-wang/4cdd1e10faa9d5d1eab9 to your computer and use it in GitHub Desktop.
balanced binary tree.
/**
* 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