Leetcode 110. Balanced Binary Tree

来源:互联网 发布:直通车如何优化 编辑:程序博客网 时间:2024/06/03 04:08

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:recursiveclass 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);    }};
0 0
原创粉丝点击