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

leetcode_110_ Balanced Binary Tree

时间:2015-02-17 10:24:07      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢技术分享


 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)自顶向下逐层累加的,而高度是从叶节点开始(其高度为1)自底向上逐层累加的。


/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    bool balance = true;
    int height(TreeNode *root)
    {
        if(!balance)
            return -1;
        if(root==NULL)
            return 0;
        else
        {
            int left_height = height(root->left)+1;
            int right_height = height(root->right)+1;
            if( abs(left_height-right_height) > 1)
                balance = false;
            else
                return left_height>right_height ? left_height : right_height;
        }
    }

public:
    bool isBalanced(TreeNode *root) {
        height(root);
        return balance;
    }
};


leetcode_110_ Balanced Binary Tree

标签:

原文地址:http://blog.csdn.net/keyyuanxin/article/details/43865245

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