zoukankan      html  css  js  c++  java
  • 平衡二叉树

    Leetcode题目描述

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

    本题中,一棵高度平衡二叉树定义为:

    一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

    示例 1:

    给定二叉树 [3,9,20,null,null,15,7]

        3
       / 
      9  20
        /  
       15   7
    返回 true 。
    

    示例 2:

    给定二叉树 [1,2,2,3,3,null,null,4,4]

          1
          / 
         2   2
        / 
       3   3
      / 
     4   4
    

    返回 false 。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/balanced-binary-tree

    自顶向下

    深度优先的解决方式,需要解决两个特性

    • 特性一,当前节点的左右子树高度差小于或者等于1
    • 特性二,左右两个子树中的节点也都要满足特性一

    可以有下面的解决方式

    • 设定一个高度函数,返回每一个节点中的左右子树的高度差h,这是一重遍历
    • 设定一个判断函数,判断,左右子树的高度h1,以及左节点的h2,右节点的h3,是否都满足小于等于1.这是第二重遍历

    自顶向下demo

    class Solution {
        public boolean isBalanced(TreeNode root) {
            if (root == null) {
                return true;
            } else {
                return Math.abs(height(root.left) - height(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
            }
        }
    
        public int height(TreeNode root) {
            if (root == null) {
                return 0;
            } else {
                return Math.max(height(root.left), height(root.right)) + 1;
            }
        }
    }
    

    自底向上

    优化一下,可以采用转变高度差的方式。不满足的条件的节点换一种方式让上层节点明白下层节点不行

    • 如果左右子节点高度差小于等于0,返回-1作为标志,令上一层节点知道此路不通。依次遍历即可完成任务

    只需要一重遍历便可

    自底向下demo

    class Solution {
        public boolean isBalanced(TreeNode root) {
            return height(root) >= 0;
        }
    
        public int height(TreeNode root) {
            if (root == null) {
                return 0;
            }
            int leftHeight = height(root.left);
            int rightHeight = height(root.right);
            if (leftHeight == -1 || rightHeight == -1 || Math.abs(leftHeight - rightHeight) > 1) {
                return -1;
            } else {
                return Math.max(leftHeight, rightHeight) + 1;
            }
        }
    }
    
    
  • 相关阅读:
    BZOJ 3744 Gty的妹子序列
    BZOJ 3872 Ant colony
    BZOJ 1087 互不侵犯
    BZOJ 1070 修车
    BZOJ 2654 tree
    BZOJ 3243 向量内积
    1003 NOIP 模拟赛Day2 城市建设
    CF865D Buy Low Sell High
    CF444A DZY Loves Physics
    Luogu 4310 绝世好题
  • 原文地址:https://www.cnblogs.com/Di-iD/p/13784836.html
Copyright © 2011-2022 走看看