题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
解题思路
递归判断即可。
代码
Python(2.7.3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17# -*- 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
if pRoot is None:
return True
return abs(self.height(pRoot.left) - self.height(pRoot.right)) <= 1 and self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
def height(self, root):
if root is None:
return 0
return max(self.height(root.left), self.height(root.right)) + 1运行时间:25ms
占用内存:5744k