首页 > 其他 > 详细

LeetCode "Balanced Binary Tree"

时间:2014-07-21 11:09:55      阅读:288      评论:0      收藏:0      [点我收藏+]

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"

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

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