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.
写一个一直比height的不难,但是是recursion of recursion,太容易stack overflow了。。。看到别人的comment和写法,学习了。。。。
当你看到recursion of recursion的时候,考虑多加一个参数,并且尝试改变或者记住他,那就简单多了。。。因为要用height,那么干脆把判断放到height里去。。。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode *root) {
bool res=true;
int h=height(root,res);
return res;
}
int height(TreeNode* root, bool& res){
if (root==0)
return 0;
int left=height(root->left, res);
int right=height(root->right,res);
if (abs(left-right)>1)
res=false;
return max(left,right)+1;
}
};