Leetcode 111.二叉树的最小深度
题目要求
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:2

示例 2:
输入:root = [2,null,3,null,4,null,5,null,6]
输出:5
层序遍历求二叉树最小深度
层序遍历所有节点并记录当前深度,遇见的第一个叶子结点(左右孩子均为null)所在的深度即为最小深度
1 2 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 40 41 42
|
class Solution { public int minDepth(TreeNode root) { int depth = 0; if (root == null) return depth; Queue<TreeNode> queue = new LinkedList<>(); queue.add(root);
while (!queue.isEmpty()) { int size = queue.size(); List<TreeNode> list = new ArrayList<>(); while (size > 0) { TreeNode node = queue.poll(); if (node.left != null) queue.add(node.left); if (node.right != null) queue.add(node.right); list.add(node); size--; } depth++; for (int i = 0; i < list.size(); i++) { if (list.get(i).left == null && list.get(i).right == null) { return depth; } } } return depth; } }
|
后序遍历求二叉树最小深度
1 2 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
| class Solution {
public int minDepth(TreeNode root) { if (root == null) { return 0; } int leftDepth = minDepth(root.left); int rightDepth = minDepth(root.right);
if (root.left == null) { return rightDepth + 1; } if (root.right == null) { return leftDepth + 1; } return Math.min(leftDepth, rightDepth) + 1; } }
|