zoukankan      html  css  js  c++  java
  • 【剑指offer】面试题55

    题目描述

    面试题55 - II. 平衡二叉树

    输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。

    示例 1:

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

        3
       /
      9  20
        / 
       15   7

    返回 true 。

     

    分析

    1.写一个计算深度的函数。然后递归求根节点左右子树的深度,作差比较。

    解题

    1.

    # 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:
            if(not root):
                return True
            a=self.countDep(root.left)
            b=self.countDep(root.right)
            diff = a-b
            if(a-b)>1 or (a-b)<-1:
                return False
            return self.isBalanced(root.left) and self.isBalanced(root.right)
    
        def countDep(self,root):
            if(not root):
                return 0
            return max(self.countDep(root.left), self.countDep(root.right))+1;
  • 相关阅读:
    置换笔记
    7.23
    Conveyor Belts
    CF #134 A~D
    Blocks && Fixing the Great wall
    Kakuro
    Deadlock Detection
    关于KeyFile的破解,含注册机源代码
    BMP位图之代码实现
    BMP位图之8位位图(三)
  • 原文地址:https://www.cnblogs.com/fuj905/p/12910548.html
Copyright © 2011-2022 走看看