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

Balanced Binary Tree

时间:2017-04-15 16:39:59      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:div   nod   null   for   return   roo   logs   balance   节点   

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

/**
 * 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

标签:div   nod   null   for   return   roo   logs   balance   节点   

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

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