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

Balanced Binary Tree

时间:2015-06-29 20:19:54      阅读:104      评论: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 a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if(root==NULL)
            return true;
        int dep = 0;
        return isBalanced(root,dep);
    }
    bool isBalanced(TreeNode* root ,int& deepth)
    {
        if(root == NULL)
        {
            deepth = 0;
            return true;
        }
        int depLeft=0;
        int depRight=0;
        bool left = isBalanced(root->left,depLeft);
        bool right = isBalanced(root->right,depRight);
        deepth = max(depLeft,depRight)+1;
        if(abs(depLeft-depRight)>1)
        {
            return false;
        }
        return left&&right;

    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

Balanced Binary Tree

标签:

原文地址:http://blog.csdn.net/leosha/article/details/46685909

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