LeetCode 104. Maximum Depth of Binary Tree
Description:
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.
Example:
Input: [1,2,3,4,2,4,3]
1 | 1 |
Output: 3
分析:
首先判断特殊情况,根节点为NULL,即返回0,这也是递归终结的条件;然后分别递归左子树和右子树;注意树的深度需要加上1。
一开始我的代码写得比较冗余,注释里我已标注,后来看了LeetCode上面的Discuss说可以一行搞定,我就发现我可以删掉大部分代码;
LeetCode上面还有使用宽度优先遍历BFS算法解决这道题的,主要利用队列的入队、出队操作,我也尝试自己编写了,代码顺便给出来,在文章末尾。
代码如下:
1 |
|
One line:
1 | class Solution { |
宽度优先遍历BFS:
1 | class Solution { |