首页 > 其他 > 详细

LeetCode 110: Balanced Binary Tree

时间:2015-03-25 16:48:59      阅读:238      评论:0      收藏:0      [点我收藏+]

题目:

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.求每个节点的深度。如果abs(左子树的深度-右子树的深度)<2,并且左右子树都是平衡的,那么该节点是平衡的

2.遍历每个节点,都满足返回true,否则返回false。

class Solution {
public:
    bool isBalanced(TreeNode *root) {
        if(root){
            return isBalanced(root->left)&&isBalanced(root->right)&&abs(depth(root->left)-depth(root->right))<2;
        }else{
            return true;
        }
    }
    int depth(TreeNode *root){
        if(!root){
            return 0;
        }
        return max(depth(root->left),depth(root->right))+1;
    }
};

解法二:

上面方法在求节点深度的时候,有重复计算,即求每个节点的深度都进行了一次到叶子节点的遍历,因此我们可以在每步将该节点的深度记录下来,即可避免该重复计算。

class Solution {
public:
    bool isBalanced(TreeNode *root) {
        int depth = 0;
        return isBalanced(root,depth);
    }
    bool isBalanced(TreeNode *root, int &depth){
        if(!root){
            depth = 0;
            return true;
        }
        int left;
        int right;
        bool isleft = isBalanced(root->left,left);
        bool isright = isBalanced(root->right,right);
        depth = max(left,right)+1;
        return isleft&&isright&&abs(left-right)<2;
    }
};

  

LeetCode 110: Balanced Binary Tree

原文:http://www.cnblogs.com/xiamaogeng/p/4365873.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!