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

[LeetCode]Balanced Binary Tree

时间:2015-02-12 21:29:37      阅读:256      评论: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.

这道题以前整理过,这里就不细写了,直接贴上代码:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool fun(TreeNode* root,int& depth){
        if(root==NULL){
            depth=0;
            return true;
        }
        int left,right;
        if(fun(root->left,left)&&fun(root->right,right)){
            int diff=left-right;
            if(abs(diff)<=1){
                depth=1+(left>right?left:right);
                return true;
            }
        }
        return false;
    }
    bool isBalanced(TreeNode *root) {
        int depth=0;
        return fun(root,depth);
    }
};

下面是以前整理的链接:平衡二叉树的判断

[LeetCode]Balanced Binary Tree

标签:平衡二叉树

原文地址:http://blog.csdn.net/kaitankedemao/article/details/43767925

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