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

LeetCode Balanced Binary Tree

时间:2014-06-24 13:32:40      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   color   for   

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode *root) {
        int h;
        return dfs(root, h);
    }
    
    bool dfs(TreeNode* root, int& height) {
        height = 0;
        if (root == NULL) {
            return true;
        }
        int lh, rh;
        if (!dfs(root->left, lh)) return false;
        if (!dfs(root->right, rh)) return false;
        lh++, rh++;
        int diff = lh - rh;
        if (diff < -1 || diff > 1) return false;
        if (diff < 0) {
            height =  rh;
        } else {
            height =  lh;
        }
        return true;
    }
};

 

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

LeetCode Balanced Binary Tree

标签:style   class   blog   code   color   for   

原文地址:http://www.cnblogs.com/lailailai/p/3805072.html

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