码迷,mamicode.com
首页 > 其他好文 > 详细

Balanced Binary Tree

时间:2015-06-25 23:04:04      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:lintcode   binary   

description

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.

http://www.lintcode.com/submission/708408/

example

Given binary tree A={3,9,20,#,#,15,7}, B={3,#,20,15,7}

A) 3 B) 3
/ \ \
9 20 20
/ \ / \
15 7 15 7

The binary tree A is a height-balanced binary tree, but B is not.

solution 1

    bool isBalancedTree(TreeNode *root,int &depth) {
    if(root == NULL) {
     return true;
    }
    int leftDepth = 0;
    bool leftResult = isBalancedTree(root->left, leftDepth);
    if(!leftResult) {
       return false;
    }
    int rightDepth = 0;
    bool rightResult = isBalancedTree(root->right, rightDepth);
    if(!rightResult) {
       return false;
    }
    if(abs(leftDepth-rightDepth) >= 2) {
       return false;
    }
    depth=(leftDepth>rightDepth)?(leftDepth+depth+1):(rightDepth+depth+1);
    return true;
}
 bool isBalanced(TreeNode *root) {
        // write your code here
     int depth=0;
      return isBalancedTree(root ,depth);
    }

explanation for solution 1

balanced tree 满足三个条件:左右子树都是,高度差小于2
既要求高度又要加判断,所以必须用到引用

solution 2

public:
    int max(int i,int j) {
    return i > j?i:j;
    }
    int getDepth(TreeNode *root) {
    if (root == NULL) {
        return 0;
    }
    int leftDepth = getDepth(root->left);
    int rightDepth = getDepth(root->right);
    if (leftDepth == -1 || rightDepth == -1 || abs(leftDepth-rightDepth) > 1) {
        return -1;
    }
    return max(leftDepth,rightDepth) + 1;
   }

    /**
     * @param root: The root of binary tree.
     * @return: True if this Binary tree is Balanced, or false.
     */
    bool isBalanced(TreeNode *root) {
        // write your code here
        return getDepth(root) != -1;
    }

explanation for soluton 2

用返回值是-1来给出子序列是否是balanced tree,更加巧妙

Balanced Binary Tree

标签:lintcode   binary   

原文地址:http://blog.csdn.net/richard_rufeng/article/details/46641987

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!