您的位置:首页 > 其它

Leetcode 110. Balanced Binary Tree

2017-02-03 14:00 399 查看
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.

s思路:

1. 判断是否balance,即:每个根节点的左子树和右子树的高度相差最多为1。考虑每个节点,可以用recursive来做。

2. 既然计算高度,那么用一个高度参数。

3. 稍微总结一下:在recursive的过程中,什么时候用reference?什么时候不用?比如这个题,就非用不可,因为统计高度,需要先recursive到底,然后把高度从底层传递到上层。我们知道,用reference是我们想把参数信息从底层往上层传递。而不需要用refenece的时候,就是我们不希望用底层的数据,上层不希望底层的参数干扰上层。这里唠叨这么多,其实就想加深印象:reference是把底层参数往上层传递的一个方法!

//方法1:recursive
class Solution {
public:
bool helper(TreeNode* root,int&height){
//
if(!root){height=0;return true;}
int h1,h2;
if(helper(root->left,h1)&&helper(root->right,h2)&&abs(h1-h2)<=1){
height=max(h1,h2)+1;
return true;
}
return false;
}

bool isBalanced(TreeNode* root) {
//
int height=0;
return helper(root,height);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode tree