首页 > 编程语言 > 详细

LeetCode 110. Balanced Binary Tree平衡二叉树 (C++)

时间:2019-05-13 00:59:49      阅读:140      评论:0      收藏:0      [点我收藏+]

题目:

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.

分析:

给定一个二叉树,判断它是否是高度平衡的二叉树。

一棵高度平衡二叉树定义为:一个二叉树每个节点的左右两个子树的高度差的绝对值不超过1。

递归求解每个节点的左右两个子树的高度差的绝对值是否超过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:
    bool isBalanced(TreeNode* root) {
        if(root == nullptr) return true;
        return abs(height(root->left, 0)-height(root->right, 0)) <= 1 && isBalanced(root->left) && isBalanced(root->right);
    }
    int height(TreeNode* root, int h) {
        if(root == nullptr) return h;
        return max(height(root->left, h+1), height(root->right, h+1));
    }
};

LeetCode 110. Balanced Binary Tree平衡二叉树 (C++)

原文:https://www.cnblogs.com/silentteller/p/10854504.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!