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.
Have you met this question in a real interview?
Yes
Example
第二种方法:
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.
这道题有两种比较典型的方法,都是递归的实现;第一种方法是每次先判断根节点是不是平衡的,然后再依次判断左右子树是不是平衡的,这样的实现,会重复计算子节点的高度;第二种方法就是边判断,边记录节点高度,先判断子树是否平衡,然后再判断根节点是否平衡,这种自底而上的方法在很多的树的相关题目中可以减少很多重复的计算(在求最近共同双亲的时候就用到了次思路);
第一种方法:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: True if this Binary tree is Balanced, or false.
*/
int GetHeight(TreeNode *root)
{
if(root == NULL)
return 0;
return max(GetHeight(root->left), GetHeight(root->right)) + 1;
}
bool isBalanced(TreeNode *root) {
// write your code here
if(root == NULL)
return true;
int lh = GetHeight(root->left);
int rh = GetHeight(root->right);
if(abs(lh - rh) > 1)
return false;
return isBalanced(root->left) && isBalanced(root->right);
}
};
第二种方法:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: True if this Binary tree is Balanced, or false.
*/
bool isBalanced(TreeNode *root, int &height){
if(root == NULL)
return true;
int left = 0, right = 0;
if(!isBalanced(root->left, left)) return false;
if(!isBalanced(root->right, right)) return false;
if(abs(left - right) > 1) return false;
height = max(left, right) + 1;
return true;
}
bool isBalanced(TreeNode *root) {
// write your code here
int height = 0;
return isBalanced(root, height);
}
};