zoukankan      html  css  js  c++  java
  • LeetCode 110. Balanced Binary Tree平衡二叉树 (C++)

    题目:

    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));
        }
    };
  • 相关阅读:
    常见Dos命令
    常用快捷键小技巧
    springboot集成JPA返回Json报错 com.fasterxml.jackson.data
    docker安装mysql 8.0.20 版本 超详细教程
    8.24 Java自学
    8.23 Java自学
    8.22 Java自学
    8.21 Java自学
    8.20 Java自学
    8.19 Java自学
  • 原文地址:https://www.cnblogs.com/silentteller/p/10854504.html
Copyright © 2011-2022 走看看