Description
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.
Example 1
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
15 7
Return true.
Example 2
Given the following tree [1,2,2,3,3,null,null,4,4]:
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
Solution 1(C++)
class Solution {
public:
int getHight(TreeNode* node){
if(!node) return 0;
return max(getHight(node->left), getHight(node->right))+1;
}
bool isBalanced(TreeNode* root) {
if(!root) return true;
return (abs(getHight(root->left)-getHight(root->right))<2) && isBalanced(root->right) && isBalanced(root->left);
}
};
算法分析
两个点,一,如何求一个树的深度;二,如何判断树是否平衡。
对于树,最好采用迭代的方法来思考,将一个根节点的问题转换成子节点的问题,所以,这样求一个树的深度,其实就是求根节点到若干叶子节点的最大距离。那么当前根节点的深度其实就等于左右子树的两个深度值中,较大的一个加一。非常简单的函数,这应该是条件反射式的基本功。
注意这里判断树是否平衡的问题,在解决了一的问题,我们只能判断这个节点的左右两个子树深度相差不超过1,但是一个平衡二叉树是每个节点,注意,每个节点的左右子树深度相差都不超过1。所以也要用迭代。
程序分析
求当前结点的深度:
int getHight(TreeNode* node){
if(!node) return 0;
return max(getHight(node->right), getHeight(node->left))+1;
}
这个应该是基本功的。