[LeetCode] 110. Balanced Binary Tree

题目链接:传送门

Description

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.

Solution

题意:

判断一棵二叉树是否 height-balanced

思路:

判断一下每个节点的左子树和右子树的高度差是否 <=1 即可

/**
 * 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:
    pair<bool, int> check(TreeNode* root) {
        if (!root)  return pair<bool, int>{true, 0};
        pair<bool, int> l = check(root->left), r = check(root->right);
        return pair<bool, int>{l.first && r.first && abs(l.second - r.second) <= 1, max(l.second, r.second) + 1};
    }
    bool isBalanced(TreeNode* root) {
        return check(root).first;
    }
};
posted @ 2018-03-01 02:05  酒晓语令  阅读(80)  评论(0编辑  收藏  举报