1957

无聊蛋疼的1957写的低端博客
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

[leetcode]Balanced Binary Tree

Posted on 2013-10-30 10:26  1957  阅读(166)  评论(0编辑  收藏  举报
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    pair<bool , int> search(TreeNode* root){
        if(root == NULL) return make_pair(true , 0);
        pair<bool , int> left = search(root -> left);
        pair<bool , int> right = search(root -> right);
        if( left.first == false || right.first == false) return make_pair(false , -1);
        int depL = left.second;
        int depR = right.second;
        if(abs(depL - depR) > 1)
            return make_pair(false , -1);
        return make_pair(true , max(depL , depR) + 1);
    }
    bool isBalanced(TreeNode *root) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        pair<bool , int> ans = search(root);
        return ans.first;
    }
};