[LeetCode] Balanced Binary Tree

题目

原题地址

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.

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

Return false.

思路

任意一个节点的左右子树深度差大于1就返回False,用一个全局变量balance表示返回值。用递归找到每个节点左右子树的深度,如果两者差大于1就将balance置为False。

python代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def depth(self, node):
        if node == None:
            return 0
        left = self.depth(node.left) # 左子树深度
        right = self.depth(node.right) # 右子树深度
        if abs(left - right) > 1:
            self.balance = False 
        return max(left, right) + 1 # 当前节点的深度为左右子树的深度最大值+1
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        self.balance = True
        self.depth(root)
        return self.balance
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容