首页 > 其他 > 详细

Balanced Binary Tree

时间:2017-04-15 16:41:18      阅读:188      评论:0      收藏:0      [点我收藏+]

方法一:使用递归的方法,使用一个变量记录以当前节点的左右节点为根节点的子树是否是平衡树,同时根据树的深度判断当前树是否为平衡树。

/**
 * 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 height(root) >= 0;
    }
    
    int height(TreeNode *root)
    {
        if(!root)
            return 0;
            
        int lt = height(root->left);
        int rt = height(root->right);
        
        if(lt == -1 || rt == -1 || abs(lt-rt) > 1)
            return -1;
        
        return max(lt, rt) + 1;
    }
};

 

Balanced Binary Tree

原文:http://www.cnblogs.com/chengyuz/p/6714583.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!