• 【leetcode】Balanced Binary Tree(middle)


    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.

    思路:

    我居然在这道题上卡了一个小时。关键是对于平衡的定义,我开始理解错了,我以为是要所有叶节点的高度差不大于1.

    但题目中的定义是如下这样的:

    Below is a representation of the tree input: {1,2,2,3,3,3,3,4,4,4,4,4,4,#,#,5,5}:

            ____1____
           /         
          2           2
         /          / 
        3    3      3   3
       /    /    /
      4  4  4  4  4  4 
     /
    5  5
    

    Let's start with the root node (1). As you can see, left subtree's depth is 5, while right subtree's depth is 4. Therefore, the condition for a height-balanced binary tree holds for the root node. We continue the same comparison recursively for both left and right subtree, and we conclude that this is indeed a balanced binary tree.

    我AC的代码:我觉得我的代码就挺好挺短的。

    bool isBalanced3(TreeNode* root){
            int depth = 0;
            return isBalancedDepth(root, depth);
        }
    
        bool isBalancedDepth(TreeNode* root, int &depth)
        {
            if(root == NULL) return true;
            int depthl = 0, depthr = 0;
            bool ans = isBalancedDepth(root->left, depthl) && isBalancedDepth(root->right, depthr) && abs(depthl - depthr) < 2;
            depth = ((depthl > depthr) ? depthl : depthr) + 1;
            return ans;
        }

    其他人的代码,对高度多遍历了一遍,会比较慢:

    bool isBalanced(TreeNode *root) {
            if (!root) return true;
            if (abs(depth(root->left) - depth(root->right)) > 1) return false;
            return isBalanced(root->left) && isBalanced(root->right);
        }
        int depth(TreeNode *node){
          if (!node) return 0;
          return max(depth(node->left) + 1, depth(node->right) + 1);
        }
  • 相关阅读:
    小程序---云开发----云函数
    小程序的基本概念-生命周期(组件 wxml)
    小程序的基本概念
    vue登录功能和将商品添加至购物车实现
    vue脚手架创建项目
    node.js评论列表和添加购物车数据库表创建
    学习脚手架--组件之间跳转与参数(组件之间参数)
    node.js 需要注意知识点
    如何查询小程序官方手册
    vue ui九宫格、底部导航、新闻列表、跨域访问
  • 原文地址:https://www.cnblogs.com/dplearning/p/4481895.html
Copyright © 2020-2023  润新知