Balanced Binary Tree

/**
 * 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,表示调用该结点之前,已有的高度。

posted @ 2015-07-22 21:08  *桔子*  阅读(165)  评论(0编辑  收藏  举报