面试题55 - I. 二叉树的深度
- 思路: 递归找左右子树的深度。
树的遍历
- 深度优先dfs: 包括前序、中序、 后序。(一般对应递归的顺序)
- 广度优先bfs: 层序遍历
其中dfs方法:
树的后序遍历 / 深度优先搜索往往利用 递归 或 栈 实现,本文使用递归实现。
观察到: 二叉树的深度 = max(左子树的最大深度,右子树的最大深度)+ 1;
##方法一 dfs
dfs算法流程
-
终止条件: 当 root 为空,说明已越过叶节点,因此返回 深度 00 。
-
递推工作: 本质上是对树做后序遍历。
计算节点 root 的 左子树的深度 ,即调用 maxDepth(root.left);
计算节点 root 的 右子树的深度 ,即调用 maxDepth(root.right);
-
返回值: 返回 此树的深度 ,即 max(maxDepth(root.left), maxDepth(root.right)) + 1。
dfs复杂度
时间复杂度 O(N) : N为树的节点数量,计算树的深度需要遍历所有节点。
空间复杂度 O(N) : 最差情况下(当树退化为链表时),递归深度可达到 N 。
public class Solution {
public int TreeDepth(TreeNode root) {
if(root == null) return 0;
return Math.max(TreeDepth(root.left), TreeDepth(root.right)) + 1;
}
}
##方法二 bfs
- 注意,该段代码在牛客网中无法通过,
import java.util.List;
import java.util.LinkedList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public int TreeDepth(TreeNode root) {
if(root == null) return 0;
// bfs
// List<TreeNode> list = new LinkedList<>(){{add(root);}};
// List<TreeNode> temp;
List<TreeNode> queue = new LinkedList<>(), temp;
queue.add(root);
int count = 0;
while(!queue.isEmpty()){
temp= new LinkedList<>();
for(TreeNode node: queue){
if(node.left != null) temp.add(node.left);
if(node.right != null) temp.add(node.right);
}
queue = temp;
count++;
}
return count;
}
}