description link example solution 1 explanation for solution 1 solution 2 explanation for soluton 2
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.
Given binary tree A={3,9,20,#,#,15,7}, B={3,#,20,15,7}
A) 3 B) 3
/
9 20 20
/ /
15 7 15 7
The binary tree A is a height-balanced binary tree, but B is not.
bool isBalancedTree(TreeNode *root,int &depth) {
if(root == NULL) {
return true;
}
int leftDepth = 0;
bool leftResult = isBalancedTree(root->left, leftDepth);
if(!leftResult) {
return false;
}
int rightDepth = 0;
bool rightResult = isBalancedTree(root->right, rightDepth);
if(!rightResult) {
return false;
}
if(abs(leftDepth-rightDepth) >= 2) {
return false;
}
depth=(leftDepth>rightDepth)?(leftDepth+depth+1):(rightDepth+depth+1);
return true;
}
bool isBalanced(TreeNode *root) {
// write your code here
int depth=0;
return isBalancedTree(root ,depth);
}
balanced tree 滿足三個條件:左右子樹都是,高度差小於2
既要求高度又要加判斷,所以必須用到引用
public:
int max(int i,int j) {
return i > j?i:j;
}
int getDepth(TreeNode *root) {
if (root == NULL) {
return 0;
}
int leftDepth = getDepth(root->left);
int rightDepth = getDepth(root->right);
if (leftDepth == -1 || rightDepth == -1 || abs(leftDepth-rightDepth) > 1) {
return -1;
}
return max(leftDepth,rightDepth) + 1;
}
/**
* @param root: The root of binary tree.
* @return: True if this Binary tree is Balanced, or false.
*/
bool isBalanced(TreeNode *root) {
// write your code here
return getDepth(root) != -1;
}
用返回值是-1來給出子序列是否是balanced tree,更加巧妙