Balanced
Binary TreeOct
9 '12
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 everynode never differ by more than 1.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <algorithm>
class Solution {
public:
int height( TreeNode *root) {
if(root==NULL) return 0;
return 1+ max( height(root->left), height(root->right) );
}
bool isBalanced(TreeNode *root) {
if(root == NULL) return 1;
if( isBalanced(root->left) && isBalanced(root->right) && abs( height(root->left) - height(root->right) ) <=1) {
return 1;
} else {
return 0;
}
}
};
public class Solution {
public boolean isBalanced(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
//input check
if(root==null) return true;
return balRec(root)!=-1;
}
private int balRec(TreeNode root) {
if(root==null) return 0;
int l = balRec(root.left);
int r = balRec(root.right);
if(l==-1 || r==-1) return -1;
if( Math.abs(l-r)>1) {
return -1;
} else {
return Math.max(l, r) +1;
}
}
}
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isBalanced(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
//input check
if(root==null) return true;
return balRec(root)!=-1;
}
private int balRec(TreeNode root) {
if(root==null) return 0;
int l = balRec(root.left);
int r = balRec(root.right);
if(l==-1 || r==-1) return -1;
if( Math.abs(l-r)>1) {
return -1;
} else {
return Math.max(l, r) +1;
}
}
}