104. Maximum Depth of Binary Tree
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 7return its depth = 3.
解法
DFS
深度优先的递归实现:
BFS
广度优先需要借助队列实现,队列用于记录每一层的所有节点,每更新一层,深度就加一,当队列为空时说明不再有下一层节点,循环结束,返回深度。
Last updated
Was this helpful?