首页 > 其他 > 详细

Balanced Binary Tree 【leetcode】

时间:2015-07-22 22:23:19      阅读:219      评论: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) {
        if(root==NULL) return true;
        int h;
        return height(root,0,h);
    }
    bool height(TreeNode * root, int h0,int &h1){
        int h2,h3;
        if(root==NULL) {h1=h0;return true;}
        if(root->left == NULL && root->right == NULL) {h1=h0+1; return true;}
        
        if(!height(root->left,h0+1,h2)) return false;
        if(!height(root->right,h0+1,h3)) return false;
        
        h1=max(h2,h3);
        return abs(h3-h2)>1?false:true;
  
    }
};

注意:想清楚参数的意义。  尤其h0,表示调用该结点之前,已有的高度。

Balanced Binary Tree 【leetcode】

原文:http://www.cnblogs.com/julie-yang/p/4668649.html

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