面试题 04.04. 检查平衡性
实现一个函数,检查二叉树是否平衡。在这个问题中,平衡树的定义如下:任意一个节点,其两棵子树的高度差不超过 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 layer_num(self, root): # 统计以root为根结点的树的高度
if root is None :
return 0
else:
return max(self.layer_num(root.left), self.layer_num(root.right)) + 1
def isBalanced(self, root: TreeNode) -> bool:
# 如果根结点是空或者它的左右结点为空,则平衡
if root is None or (root.left is None and root.right is None):
return True
# 如果左右子树平衡而且左右子树的层数(高度)差不大于1则平衡
if (self.isBalanced(root.left) and self.isBalanced(root.right)
and abs(self.layer_num(root.left) - self.layer_num(root.right)) <= 1):
return True
# 否则不平衡
else:
return False
这种方法效果不好,因为递归本身的效率就不高,这里不止用了一种递归,isBalanced和layer_num都用到了递归,所以导致效率低下。
方法二:
class Solution:
def isBalanced(self, root):
return self.getHeight(root, 0) != -1
def getHeight(self, head, depth):
if head == None:
return depth
left = self.getHeight(head.left, depth)
if left == -1:
return -1
right = self.getHeight(head.right, depth)
if right == -1:
return -1
if abs(left - right) > 1:
return -1
return max(left, right) + 1