zoukankan      html  css  js  c++  java
  • [LeetCode] 110. 平衡二叉树

    题目链接 : https://leetcode-cn.com/problems/balanced-binary-tree/

    题目描述:

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

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

    一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过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 。
    

    思路:

    这道题是求树的高度的延伸版, 我们只要求左右子树相差的高度是否超过1,就可以了!

    首先,要自顶向下方法,如下代码:

    class Solution:
        def isBalanced(self, root: TreeNode) -> bool:
            if not root:
                return True
            return abs(self.height(root.right)-self.height(root.left))<2 and self.isBalanced(root.left) and self.isBalanced(root.right)
    	# 求高度
        def height(self, node):
            if not node:
                return 0
            return 1+max(self.height(node.right),self.height(node.left))
    

    上面的方法要不断递归左右子树, 有重复部分,所以时间复杂度为(O(n^2))

    下面用自底向上,直接看代码就能理解了!

    时间复杂度为(O(n))

    代码:

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def isBalanced(self, root: TreeNode) -> bool:
            self.res = True
            def helper(root):
                if not root:
                    return 0
                left = helper(root.left) + 1
                right = helper(root.right) + 1
                #print(right, left)
                if abs(right - left) > 1: 
                    self.res = False
                return max(left, right)
            helper(root)
            return self.res
    

    java

    public class BalancedBinaryTree {
        boolean res = true;
    
        public boolean isBalanced(TreeNode root) {
    
            helper(root);
            return res;
    
        }
    
        private int helper(TreeNode root) {
            if (root == null) return 0;
            int left = helper(root.left) + 1;
            int right = helper(root.right) + 1;
            if (Math.abs(right - left) > 1) res = false;
            return Math.max(left, right);
        }
    }
    
  • 相关阅读:
    windows 7 codepage id name 名称
    最大团
    三分的多种写法及对应的精度 三分套三分原理
    AC自动机
    c++ queue
    lca 欧拉序+rmq(st) 欧拉序+rmq(线段树) 离线dfs 倍增
    node *p,*q
    dfs序和欧拉序
    P3861 8月月赛A
    洛谷P3862 8月月赛B
  • 原文地址:https://www.cnblogs.com/powercai/p/11107470.html
Copyright © 2011-2022 走看看