给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
示例 1:

1 2
| 输入:root = [3,9,20,null,null,15,7] 输出:2
|
示例 2:
1 2
| 输入:root = [2,null,3,null,4,null,5,null,6] 输出:5
|
提示:
- 树中节点数的范围在
[0, 105]
内
-1000 <= Node.val <= 1000
递归
后续遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution { public int minDepth(TreeNode root) { if(root==null) return 0; int left_depth = minDepth(root.left); int right_depth = minDepth(root.right); if(root.left == null && root.right != null){ return 1 + right_depth; } if(root.right==null&&root.left!=null){ return 1 + left_depth; }
return 1 + Math.min(left_depth,right_depth); } }
|
前序遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Solution { int min = Integer.MAX_VALUE; public int minDepth(TreeNode root) { if(root == null) return 0; traversal(root, 1); return min; }
public void traversal(TreeNode root, int d){ if(root == null) return; if(root.left == null && root.right == null){ min = Math.min(min, d); } traversal(root.left, d+1); traversal(root.right, d+1); } }
|
层次遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public int minDepth(TreeNode root) { if(root == null) return 0; int depth = 0; Queue<TreeNode> que = new LinkedList<>(); que.offer(root); while(!que.isEmpty()){ int size = que.size(); depth++; for(int i = 0 ; i<size ;i++){ TreeNode node = que.poll(); if(node.left==null && node.right==null){ return depth; } if(node.left!=null) que.offer(node.left); if(node.right!=null) que.offer(node.right); } } return depth; } }
|