categories: [Blog,Algorithm]


111. 二叉树的最小深度

给定一个二叉树,找出其最小深度。

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明:叶子节点是指没有子节点的节点。

image.png

示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:2

示例 2:
输入:root = [2,null,3,null,4,null,5,null,6]
输出:5

  1. public int minDepth1(TreeNode root) {
  2. if (root == null) {
  3. return 0;
  4. }
  5. if (root.left == null && root.right == null) {
  6. return 1;
  7. }
  8. int min_depth = Integer.MAX_VALUE;
  9. if (root.left != null) {
  10. min_depth = Math.min(minDepth(root.left), min_depth);
  11. }
  12. if (root.right != null) {
  13. min_depth = Math.min(minDepth(root.right), min_depth);
  14. }
  15. return min_depth + 1;
  16. // 作者:LeetCode-Solution
  17. // 链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/solution/er-cha-shu-de-zui-xiao-shen-du-by-leetcode-solutio/
  18. }

  1. class QueueNode {
  2. TreeNode node;
  3. int depth;
  4. public QueueNode(TreeNode node, int depth) {
  5. this.node = node;
  6. this.depth = depth;
  7. }
  8. }
  9. public int minDepth(TreeNode root) {
  10. if (root == null) {
  11. return 0;
  12. }
  13. Queue<QueueNode> queue = new LinkedList<QueueNode>();
  14. queue.offer(new QueueNode(root, 1));
  15. while (!queue.isEmpty()) {
  16. QueueNode nodeDepth = queue.poll();
  17. TreeNode node = nodeDepth.node;
  18. int depth = nodeDepth.depth;
  19. if (node.left == null && node.right == null) {
  20. return depth;
  21. }
  22. if (node.left != null) {
  23. queue.offer(new QueueNode(node.left, depth + 1));
  24. }
  25. if (node.right != null) {
  26. queue.offer(new QueueNode(node.right, depth + 1));
  27. }
  28. }
  29. return 0;
  30. }
  31. 作者:LeetCode-Solution
  32. 链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/solution/er-cha-shu-de-zui-xiao-shen-du-by-leetcode-solutio/
  1. public int minDepth(TreeNode root) {
  2. if (root == null) return 0;
  3. else if (root.left == null) return minDepth(root.right) + 1;
  4. else if (root.right == null) return minDepth(root.left) + 1;
  5. else return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
  6. // 作者:LeetCode-Solution
  7. // 链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/solution/er-cha-shu-de-zui-xiao-shen-du-by-leetcode-solutio/
  8. }
  1. public int minDepth(TreeNode root) {
  2. if (root == null) {
  3. return 0;
  4. }
  5. // 计算左子树的深度
  6. int left = minDepth(root.left);
  7. // 计算右子树的深度
  8. int right = minDepth(root.right);
  9. // 如果左子树或右子树的深度不为 0,即存在一个子树,那么当前子树的最小深度就是该子树的深度+1
  10. // 如果左子树和右子树的深度都不为 0,即左右子树都存在,那么当前子树的最小深度就是它们较小值+1
  11. return (left == 0 || right == 0) ? left + right + 1 : Math.min(left, right) + 1;
  12. }