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

LeetCode "Balanced Binary Tree"

时间:2014-07-21 11:10:03      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   re   c   

Another recursion problem.

class Solution {
public:
    int getHeight(TreeNode *p)
    {
        if (!p) return 0;

        int hL = 1;
        if (p->left) hL = 1 + getHeight(p->left);
        int hR = 1;
        if (p->right) hR = 1 + getHeight(p->right);

        return (hL > hR ? hL : hR);
    }
    bool isBalanced(TreeNode *root) {
        if (!root || (!root->left && !root->right)) return true;

        bool bLeft = isBalanced(root->left);
        if (!bLeft) return false;
        bool bRight = isBalanced(root->right);
        if (!bRight) return false;
        {
            int hL = getHeight(root->left);
            int hR = getHeight(root->right);
            if (abs(hL - hR) < 2) return true;
        }
        return false;
    }
};

LeetCode "Balanced Binary Tree",布布扣,bubuko.com

LeetCode "Balanced Binary Tree"

标签:style   blog   color   io   re   c   

原文地址:http://www.cnblogs.com/tonix/p/3857681.html

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