Minimum Depth of Binary Tree

描述

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

分析

递归版

  1. // Minimum Depth of Binary Tree
  2. // 递归版,时间复杂度O(n),空间复杂度O(logn)
  3. public class Solution {
  4. public int minDepth(TreeNode root) {
  5. return minDepth(root, false);
  6. }
  7. private static int minDepth(TreeNode root, boolean hasbrother) {
  8. if (root == null) return hasbrother ? Integer.MAX_VALUE : 0;
  9. return 1 + Math.min(minDepth(root.left, root.right != null),
  10. minDepth(root.right, root.left != null));
  11. }
  12. }

迭代版

  1. // Minimum Depth of Binary Tree
  2. // 迭代版,时间复杂度O(n),空间复杂度O(logn)
  3. public class Solution {
  4. public int minDepth(TreeNode root) {
  5. if (root == null) return 0;
  6. int result = Integer.MAX_VALUE;
  7. Stack<Pair> s = new Stack<>();
  8. s.push(new Pair(root, 1));
  9. while (!s.empty()) {
  10. final Pair p = s.pop();
  11. TreeNode node = p.node;
  12. int depth = p.depth;
  13. if (node.left == null && node.right == null)
  14. result = Math.min(result, depth);
  15. if (node.left != null && result > depth) // 深度控制,剪枝
  16. s.push(new Pair(node.left, depth + 1));
  17. if (node.right != null && result > depth) // 深度控制,剪枝
  18. s.push(new Pair(node.right, depth + 1));
  19. }
  20. return result;
  21. }
  22. static class Pair {
  23. TreeNode node;
  24. int depth;
  25. public Pair(TreeNode node, int depth) {
  26. this.node = node;
  27. this.depth = depth;
  28. }
  29. }
  30. }

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/binary-tree/recursion/minimum-depth-of-binary-tree.html