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

每日一小练——因子分解

时间:2014-05-22 11:42:14      阅读:253      评论:0      收藏:0      [点我收藏+]

标签:leetcode   oj   算法   

1、


Balanced Binary Tree

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则非,如果小于等于1则是,递归判断左右子树。

class Solution {
public:
    bool isBalanced(TreeNode *root) {
        if(!root){
            return true;
        }
        isBalancedTree = true;
        calDepth(root);
        return isBalancedTree;
    }
    int calDepth(TreeNode* root){
        if(!isBalancedTree){
            return 0;
        }
        if(!root->left && !root->right){
            return 1;
        }
        int left = 0;
        int right = 0;
        if(root->left){
            left = calDepth(root->left);
        }
        if(root->right){
            right = calDepth(root->right);
        }
        if(abs(left-right) > 1){
            isBalancedTree = false;
        }
        return max(right,left)+1;
    }
    bool isBalancedTree;
};

每日一小练——因子分解,布布扣,bubuko.com

每日一小练——因子分解

标签:leetcode   oj   算法   

原文地址:http://blog.csdn.net/zhurui_idea/article/details/26169133

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