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.
平衡二叉树: | 左子树高度 - 右子树高度 | <= 1。
这个问题用递归的思想就是如果最根的树是平衡的,再看左右子树也是平衡的,那整体就是平衡的,这就很简单了。但是高兴之余我们想想,这样似乎走了重复的老路,因为我们在判定最根树是否为平衡树的时候,就已经从叶节点走过一回了,再判断其子树是否平衡的时候,我们还的从叶子结点走一遍,这要树的深度很深的时候,代价就有点小高,我们能不能在第一次从叶节点向上走的时候,就判断其子树是否满足,如若不满足,就直接从递归处层层返回?试试。
class Solution {
public:
int hight(TreeNode *root,bool &go_on)
{
if(!root) return 0;
int left = hight(root->left,go_on);
int right = hight(root->right,go_on);
if(abs(left - right) > 1) go_on = false;
return max(left,right) + 1;
}
bool isBalanced(TreeNode *root) {
if(!root) return true;
bool go_on = true;
int left = hight(root->left,go_on);
if(!go_on) return false;
int right = hight(root->right,go_on);
if(!go_on || abs(left - right) > 1) return false;
return true;
}
};
这个代码有点丑陋,是直接在leetcode线上敲的,不过思路还算清晰,从叶子向上每走一步,我们都检查当前生成的子树是否满足平衡条件,若满足则继续进行,若不满足,右子树也甭看了,直接返回结果就行了,因为在左边已经发现异常了。