题目描述:
输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
示例 1:
给定二叉树 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回 true 。
示例 2:
给定二叉树 [1,2,2,3,3,null,null,4,4]
1
/ \
2 2
/ \
3 3
/ \
4 4
返回 false 。
限制:1 <= 树的结点个数 <= 10000
平衡二叉树指二叉树的每个节点的左右子树的高度差的绝对值不超过1。首先,我们需要求得某个子树的深度,由之前的解题知道:一棵树的深度 = max(左子树深度,右子树深度) + 1
;另外,另外,判断当前子树是否是平衡二叉树,只需要判断左右子树深度差的绝对值是否小于等于1:
- 如果满足,则继续判断左子树和右子树
- 否则,说明给定的树不是平衡二叉树
# -*- 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):
# write code here
def depth(root):
if not root: return 0
return max(depth(root.left), depth(root.right)) + 1
def isBalanced(root):
if not root: return True
return isBalanced(root.left) and isBalanced(root.right) and abs(depth(root.left) - depth(root.right)) <= 1
if not pRoot: return True
return isBalanced(pRoot)
另一种复杂的解法…
# -*- 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): # write code here def TreeDepth( pRoot): # write code here global maxdepth maxdepth = 0 def DfsTree(root,depth = 0): global maxdepth if root: depth+=1 isLeaf = None if root.left == None and root.right == None: isLeaf = True if root.left: DfsTree(root.left, depth) if root.right: DfsTree(root.right, depth) if isLeaf and depth > maxdepth: maxdepth = depth if pRoot == None: return 0 else: DfsTree(pRoot) return maxdepth def isBalanced(root): if root is None: return True return isBalanced(root.left) and isBalanced(root.right) and abs(TreeDepth(root.left) - TreeDepth(root.right)) <= 1 if pRoot is None: return True return isBalanced(pRoot) ```