题目
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
思考
- 解法一:递归
如果一棵二叉树是平衡二叉树,那么他的左子树和右子树都是平衡二叉树,并且左子树和右子树的深度差小于等于一。因此可以利用递归法来实现。递归的base_condition是空树,空树也是平衡二叉树。 - 解法二:后序遍历
转载请注明:剑指Offer(三十九):平衡二叉树 | Jack Cui
如果我们用后序遍历的方式遍历二叉树的每一个结点,在遍历到一个结点之前我们就已经遍历了它的左右子树。只要在遍历每个结点的时候记录它的深度(某一结点的深度等于它到叶结点的路径的长度),我们就可以一边遍历一边判断每个结点是不是平衡的。
代码
- 解法一
# -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def IsBalanced_Solution(self, pRoot):
if not pRoot: #空树也是平衡二叉树
return True
return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right) and abs(self.countLayer(pRoot.left)-self.countLayer(pRoot.right)) <= 1
def countLayer(self, pRoot):
if not pRoot:
return 0
if pRoot and pRoot.left is None and pRoot.right is None:
return 1
queue = [(pRoot,1)]
while len(queue) :
node,layer = queue.pop(0)
if node.left not in queue and node.left is not None:
queue.append((node.left,layer+1))
if node.right not in queue and node.right is not None:
queue.append((node.right,layer+1))
return layer