Skip to content

Latest commit

 

History

History
99 lines (77 loc) · 2.62 KB

0110. Balanced Binary Tree.md

File metadata and controls

99 lines (77 loc) · 2.62 KB

题目

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 left and right subtrees of every node differ in height by no 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

我的思路

这道题要求判断一个二叉树是否为平衡二叉树。平衡二叉树的定义为:任意一个节点的两棵子树深度差不超过1。我首先写一个求深度的函数,然后用递归来判断:如果当前节点符合条件,就判断它的左节点和右节点是否符合条件。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isBalanced(self, root: TreeNode) -> bool:
        if not root:
            return True
        if self.depth(root.left) - self.depth(root.right) > 1 or self.depth(root.right) - self.depth(root.left) > 1:
            return False
        else:
            return self.isBalanced(root.left) and self.isBalanced(root.right)
    
    def depth(self, root: TreeNode) -> int:
        if not root:
            return 0
        else:
            return (1 + max(self.depth(root.left),self.depth(root.right)))

我的方法速度较慢,查看别人更快的方法。更快的方法是在求深度的那个函数中就作判断:如果两棵子树深度相差超过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
       
        def getDepth(root):  
            if not root:
                return 0
            ld = 0
            rd = 0
            ld = getDepth(root.left)
            rd = getDepth(root.right)
            if (ld==-1 or rd==-1):
                return -1
            if abs(ld - rd) > 1:
                return -1
            return max(ld+1, rd+1)
        
        l = getDepth(root.left)
        r = getDepth(root.right)
        if l==-1 or r==-1 or (abs(l-r)>1):
            return False
        return True