104. 二叉树的最大深度
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
![](https://img-blog.csdnimg.cn/img_convert/2eacfd2bfa092f6c9b0f7f671b196a49.png)
返回它的最大深度 3 。
思路一:递归
递归计算左右子树的高度,树的高度等于左右子树的最大高度加一
1 /**
2 * Definition for a binary tree node.
3 * public class TreeNode {
4 * int val;
5 * TreeNode left;
6 * TreeNode right;
7 * TreeNode(int x) { val = x; }
8 * }
9 */
10 class Solution {
11 public int maxDepth(TreeNode root) {
12 if(root == null){
13 return 0;
14 }
15 // 递归计算左右子树的高度,树的高度等于左右子树的最大高度加一
16 int leftDep = maxDepth(root.left);
17 int rightDep = maxDepth(root.right);
18 return Math.max(leftDep, rightDep) + 1;
19 }
20 }
力扣测试时间为0ms, 空间为39.5mb, 这种算法简单高效
复杂度分析:
时间复杂度:需要对每个结点进行访问,所以时间复杂度为O(n)
空间复杂度:O(h), h最大为n(当树退化成链表时),所以空间复杂度为O(n), 在最好的情况下,也就是树是平衡的,这样数的高度就是O(logn), 此时空间复杂度就为O(logn)
思路二:BFS迭代
1. 外层循环每次迭代一层
2. 内层循环弹出该层的所有结点,入队下一层的所有结点
1 // BFS计算深度
2 class Solution {
3 public int maxDepth(TreeNode root) {
4 if(root == null){
5 return 0;
6 }
7 Queue<TreeNode> queue = new LinkedList<>();
8 queue.offer(root);
9 int dept = 0;
10 while(!queue.isEmpty()){
11 int count = queue.size(); // 当前层次的结点个数
12 dept++;
13 // 弹出该层的所有结点,入队下一层的所有结点
14 for(int i = 0; i < count; i++){
15 TreeNode node = queue.poll();
16 if(node.left != null)
17 queue.offer(node.left);
18 if(node.right != null)
19 queue.offer(node.right);
20 }
21 }
22 return dept;
23 }
24 }
力扣测试时间为:1ms, 空间为37.7MB
复杂度分析:
时间复杂度:对每个结点进行了一次遍历,所以时间复杂度为O(n)
空间复杂度:空间复杂度就是队列的大小,队列存储的是一层的结点,最坏情况下,只有两层,这样空间复杂度就为O(n/2), 也就是O(n)
BFS的另一种写法
用一个Pair<TreeNode, Integer> 来表示一个结点,Integer表示该结点的高度,将这样的结点存入queue中,这样每次获得结点的同时都能获得该结点的高度
1 class Solution {
2 public int maxDepth(TreeNode root) {
3 if(root == null){
4 return 0;
5 }
6 Queue<Pair<TreeNode, Integer>> queue = new LinkedList<>();
7 queue.offer(new Pair(root, 1));
8 int dept = 0;
9 while(!queue.isEmpty()){
10 // 弹出一个结点
11 Pair<TreeNode, Integer> top = queue.poll();
12 root = top.getKey();
13 int currentDep = top.getValue();
14 dept = Math.max(currentDep, dept); // 更新最大高度
15 // 将左右孩子结点入队,但是高度标记为父节点加一
16 if(root != null){
17 if(root.left != null)
18 queue.offer(new Pair(root.left, currentDep + 1));
19 if(root.right != null)
20 queue.offer(new Pair(root.right, currentDep + 1));
21 }
22 }
23 return dept;
24 }
25 }
力扣测试的时间为:3ms, 空间为 39.3mb, 是三种方法中的最慢的一种
复杂度分析:
空间复杂度和时间复杂度都为O(n)