二叉树的最小深度

二叉树的最小深度

问题

这个题目说的是,给你一棵二叉树,你要找到从根节点到最近的叶子节点的深度。

比如说,给你的二叉树是:

     1
   /   \
  2     4
       / \
      8  16

这棵树有 3 个叶子节点,分别是 2,8,16。最近的叶子节点是 2,根节点到 2 共有两个节点,因此最小深度是 2。

再比如说,给你的二叉树是:

  1
   \
    2
     \
      4

这棵树唯一的叶子节点是 4,根节点到它共有 3 个节点,因此最小深度是 3

代码

public class AlgoCasts {

  public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
      val = x;
    }
  }

  // Time: O(n), Space: (n)
  public int minDepth(TreeNode root) {
    if (root == null) return 0;
    if (root.left == null && root.right == null) return 1;
    if (root.left == null) return minDepth(root.right) + 1;
    if (root.right == null) return minDepth(root.left) + 1;
    return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
  }

  // Time: O(n), Space: O(n)
  public int minDepthIterative(TreeNode root) {
    if (root == null) return 0;
    Queue<TreeNode> q = new LinkedList<>();
    q.add(root);
    int depth = 1;

    while (!q.isEmpty()) {
      int size = q.size();
      for (int i = 0; i < size; ++i) {
        TreeNode s = q.poll();
        if (s.left == null && s.right == null) return depth;
        if (s.left != null) q.add(s.left);
        if (s.right != null) q.add(s.right);
      }
      ++depth;
    }

    return -1;
  }

}

  转载请注明: ForwardXu 二叉树的最小深度

 上一篇
跳数组 跳数组
跳数组问题 这个题目说的是,给你一个非负整数数组,数组中的每个数字表示那个位置上可以向后跳的最大步数。一开始你站在下标为 0 的位置,你要判断是否可以跳到数组最后的位置。 比如说,给你的数组 a 是: 2, 4, 0, 1, 2 一开始
2018-12-16
下一篇 
不用+-求两数之和 不用+-求两数之和
不用+/-求两数之和问题 这个题目说的是,给你两个整数,在不使用 +/- 这两个运算符的前提下,求它们的和。 代码 public class AlgoCasts { public int getSumRecursive(int a,
2018-12-16
  目录