题目
我的代码
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self):
self.count=0
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def DFS(tree,count):
if tree:
count+=1
count=max(DFS(tree.left,count),DFS(tree.right,count))
return count
else:
return count
return DFS(root,0)
优秀代码
好像差不多。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
height = 0
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def setHeight(root, height):
if root:
if self.height < height:
self.height = height
setHeight(root.left, height+1)
setHeight(root.right, height+1)
setHeight(root, self.height+1)
return self.height