思路:递归遍历就行了
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def search(self, root: TreeNode, depth : int):
if(root == None):
return depth
return max(self.search(root.left, depth + 1),self.search(root.right, depth + 1))
def maxDepth(self, root: TreeNode) -> int:
return self.search(root, 0)
感觉自己有点傻逼,还是这个好
class Solution:
def maxDepth(self, root):
if root is None:
return 0
else:
left_height = self.maxDepth(root.left)
right_height = self.maxDepth(root.right)
return max(left_height, right_height) + 1