110. Balanced Binary Tree

2018-06-19  本文已影响0人  SilentDawn

Problem

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as:

a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example

Given the following tree [3,9,20,null,null,15,7]:

    3
   / \
  9  20
    /  \
   15   7

Return false.

Given the following tree [1,2,2,3,3,null,null,4,4]:

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

Return true.

Code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
static int var = [](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
class Solution {
public:
    int height = 0;
    bool isBalanced(TreeNode* root) {
        if(root == NULL)
            return true;
        int height = 1;
        return checkBalanced(root,height);
    }
    bool checkBalanced(TreeNode* root, int& height){
        if(!root)
            return true;
        int left_height = 0;
        int right_height = 0;
        if(!checkBalanced(root->left,left_height))
            return false;
        if(!checkBalanced(root->right,right_height))
            return false;
        if(abs(left_height-right_height)>1)
            return false;
        height = max(left_height,right_height)+1;
        return true;
        
    }
};

Result

110. Balanced Binary Tree.png
上一篇下一篇

猜你喜欢

热点阅读