LeetCode 110. Balanced Binary Tr

2019-02-28  本文已影响0人  cb_guo

题目描述

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 1:

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

    3
   / \
  9  20
    /  \
   15   7
Return true.

Example 2:

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

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4
Return false.

题目思路

代码 C++

/**
 * 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 depth_left  = Depth(root->left);
        int depth_right = Depth(root->right);
        int tt = depth_left - depth_right;
        if(tt < -1 || tt > 1){
            return false;
        }
        return isBalanced(root->left) && isBalanced(root->right);
    }
    
    int Depth(TreeNode* root){
        if(root == NULL){
            return 0;
        }
        
        int depth_left  = Depth(root->left);
        int depth_right = Depth(root->right);
        
        return (depth_left > depth_right) ? (depth_left+1) : (depth_right+1);
    }
};
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        int depth = 0;
        return core(root, &depth);
    }
    
    bool core(TreeNode* root, int* depth){
        if(root == NULL){
            *depth = 0;
            return true;
        }
        
        int left, right;
        if(core(root->left, &left) && core(root->right, &right)){
            int diff = left - right;
            if(diff >= -1 && diff <= 1){
                *depth = (left > right) ? left+1 : right+1;
                return true;
            }
        }
        return false;
    }
};

总结展望

上一篇下一篇

猜你喜欢

热点阅读