• 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));
        }
    };
  • 相关阅读:
    nvm的安装与使用
    webpack中import动态设置webpackChunkName方法
    css在背景图下加渐变色
    js实现时间戳转换
    js实现随机数和随机数组
    js实现导航自动切换请求数据
    jq、js获取select中option上的value值以及文本值
    js、jq实现select 下拉选择更多
    软件测试
    php
  • 原文地址:https://www.cnblogs.com/silentteller/p/10854504.html
Copyright © 2020-2023  润新知