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?
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);
}
};