您的位置:首页 > 编程语言 > Python开发

平衡二叉树[剑指offer]之python实现

2016-10-12 22:24 357 查看
题目描述

输入一棵二叉树,判断该二叉树是否是平衡二叉树。

题目链接

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
def getDepth(self , Root):
if Root == None:
return 0;
lDepth = self.getDepth(Root.left);
rDepth = self.getDepth(Root.right);
return max(lDepth , rDepth) + 1;

def IsBalanced_Solution(self, pRoot):
if not pRoot:
return True
lDepth = self.getDepth(pRoot.left);
rDepth = self.getDepth(pRoot.right);
diff = lDepth - rDepth;
if diff < -1 or diff > 1:
return False;
return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right);


求解:为什么用val不可以记录树的高度?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python