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

Balanced Binary Tree -- leetcode

时间:2015-05-09 13:29:28      阅读:101      评论: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.


基本思路:

判断二叉树是否平衡,判断其左右子树深度差距总不超过1.

引入一辅助函数,其返回树的深度。

同时,如果其发现自己左右子树已经不平稀,则返回-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) {
        return helper(root) != -1;
    }
    
    int helper(TreeNode *root) {
        if (!root) return 0;
        const int left = helper(root->left);
        if (left == -1) 
            return left;
        const int right = helper(root->right);
        if (right == -1 || abs(left-right)>1) 
            return -1;
        return max(left, right) + 1;
    }
};


Balanced Binary Tree -- leetcode

标签:二叉树   平衡   

原文地址:http://blog.csdn.net/elton_xiao/article/details/45600141

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