104. Maximum Depth of Binary Tree(二叉树深度-DFS方法)

2,395次阅读

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

3
/ \
9  20
/  \
15   7

return its depth = 3.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
#深度优先
def _dfs(self, node, max_level):

#如果当前节点的左右节点都不存在，则直接返回
if not node.left and not node.right:
return max_level
#节点都存在的时候需要继续递归求解
elif node.left and node.right:
return max(self._dfs(node.left,max_level+1),self._dfs(node.right,max_level+1))
#只存在左节点
elif node.left:
return self._dfs(node.left,max_level+1)
#只存在右节点
else:
return self._dfs(node.right,max_level+1)
def maxDepth(self, root: TreeNode) -> int:

#深度优先
if not root:
return 0
max_level = self._dfs(root,1)
return max_level