目录/Table of Content
110. Balanced Binary Tree (平衡二叉树)
大家好,我是一个喜欢研究算法、机械学习和生物计算的小青年,我的CSDN博客是:一骑代码走天涯
如果您喜欢我的笔记,那么请点一下关注、点赞和收藏。如果內容有錯或者有改进的空间,也可以在评论让我知道。😄
题目描述
平衡二叉树 (balanced binary tree) 意思是树中每一個子树,它的左右子树的最大高度都不会相差大于1。现在,题目给一棵二叉树,编写一个函数来判断这树是否平衡二叉。
题目原文(英语)
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]
Return true.
3
/ \
9 20
/ \
15 7
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]
Return false.
1
/ \
2 2
/ \
3 3
/ \
4 4
解题方式
简单来说,首先我们要搞清楚每一棵子树是否都是平衡,才能够判断出主树是否平衡。因此,就写了一个计算任何子树深度的函数,再用递迴 (Recursion)的方法判断主树是否平衡,如果平衡则返回正数,反之 -1。
最后只需判別这个帮助函数是不是 -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:
return self.helper_countdist(root) != -1
# Helping to count maximum depth of binary tree, return -1 is not balanced
def helper_countdist(self, root: TreeNode):
if not root:
return 0
left = self.helper_countdist(root.left)
right = self.helper_countdist(root.right)
if left == -1 or right == -1 or abs(left - right) > 1:
return -1
return 1 + max(left, right)