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

Python实现二叉树的深度

2017-06-23 13:24 155 查看
python实现二叉树的深度搜索

class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None

class Solution(object):
def isBalanced(self, root):
if root==None:
return 0
leftheight=self.isBalanced(root.left)
rightheight=self.isBalanced(root.right)
if leftheight>=rightheight:
return leftheight+1
else:
return rightheight+1

input_3=TreeNode(3)
input_4=TreeNode(4)
input_5 = TreeNode(5)
input_5.left=input_3
input_5.right=input_4
input_18 = TreeNode(18)
input_all = TreeNode(2)
input_all.left = input_5
input_all.right = input_18
slu_ = Solution()
print input_all
t = slu_.isBalanced(input_all)
print t
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: