题目:
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.
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
15 7
Given the following tree [1,2,2,3,3,null,null,4,4]:
1
/ \
2 2
/ \
3 3
/ \
4 4
题目分析:平衡二叉树的判断,需要统计到左右子树的情况,看左右子树的高度差,所以,需要返回的信息是左右子树的高度的问题。
python代码实现:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root == None:
return True
left, right = self.height(root)
if abs(left - right) > 1:
return False
if root.left:
if self.isBalanced(root.left) == False:
return False
if root.right:
if self.isBalanced(root.right) == False:
return False
return True
def height(self, root):
if root == None:
return (0, 0)
if root.left == None and root.right == None:
return (0, 0)
if root.left and root.right == None:
return (1 + max(self.height(root.left)), 0)
if root.right and root.left == None:
return (0, 1 + max(self.height(root.right)))
return (1 + max(self.height(root.left)), 1 + max(self.height(root.right)))
看一下大佬的程序:
class Solution(object):
def isBalanced(self, root):
def check(root):
if root is None:
return 0
left = check(root.left)
right = check(root.right)
if left == -1 or right == -1 or abs(left - right) > 1:
return -1
return 1 + max(left, right)
return check(root) != -1
程序里递归,还是第一次见呀,好好学习一下这种写法。
class Solution(object):
def isBalanced(self, root):
stack, node, last, depths = [], root, None, {}
while stack or node:
if node:
stack.append(node)
node = node.left
else:
node = stack[-1]
if not node.right or last == node.right:
node = stack.pop()
left, right = depths.get(node.left, 0), depths.get(node.right, 0)
if abs(left - right) > 1: return False
depths[node] = 1 + max(left, right)
last = node
node = None
else:
node = node.right
return True
这个是采用迭代的方法来写的,也是晚上需要好好看一下的。