题目描述
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树 [3,9,20,null,null,15,7],
返回它的最大深度 3 。
题解
题意分析
- 二叉树的深度,指二叉树头节点到最远叶子节点路径中的节点数。
- 给定根节点,指从根节点开始遍历计算。
深度优先遍历(DFS) + 递归
思路
- 从头节点开始递归遍历左右子树的深度。
- 每个节点的深度为左右子树深度的最大值加自身。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 
 | class TreeNode {int val;
 TreeNode left;
 TreeNode right;
 TreeNode(int x) {
 val = x;
 }
 }
 
 public int maxDepth01(TreeNode root) {
 
 if (root == null) {
 return 0;
 }
 
 int left = maxDepth01(root.left);
 int right = maxDepth01(root.right);
 
 return Math.max(left, right) + 1;
 }
 
 | 
广度优先遍历(BFS) + 队列
思路
- 按层级遍历二叉树,每遍历一层,二叉树深度 +1 。
- 遍历完所有层级,返回最终的二叉树深度。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 
 | class TreeNode {int val;
 TreeNode left;
 TreeNode right;
 TreeNode(int x) {
 val = x;
 }
 }
 
 public int maxDepth02(TreeNode root) {
 
 if (root == null) {
 return 0;
 }
 
 Queue<TreeNode> queue = new LinkedList<>();
 
 queue.add(root);
 int ans = 0;
 while (!queue.isEmpty()) {
 
 int size = queue.size();
 while (size > 0) {
 
 TreeNode node = queue.poll();
 size--;
 
 if (node.left != null) {
 queue.offer(node.left);
 }
 if (node.right != null) {
 queue.offer(node.right);
 }
 }
 
 ans++;
 }
 return ans;
 }
 
 |