题解 | #二叉树的深度#
二叉树的深度
http://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b
递归可以解决
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param pRoot TreeNode类
# @return int整型
#
class Solution:
def function(self,tree):
if tree.left and tree.right:
leftdepth=self.function(tree.left)
rightdepth=self.function(tree.right)
if leftdepth>=rightdepth:
return leftdepth+1
else:
return rightdepth+1
elif tree.left:
return self.function(tree.left)+1
elif tree.right:
return self.function(tree.right)+1
else:
return 1
def TreeDepth(self , pRoot: TreeNode) -> int:
cur=pRoot
#先排除特殊情况
if pRoot==None:
return 0
else:
return self.function(cur)
# write code here