[LeetCode] 111. 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.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / 
  9  20
    /  
   15   7

return its minimum depth = 2.

二叉树的最小深度。题目即是题意。我这里提供两种做法。

第一种思路是后序遍历。如果左孩子和右孩子有一个为NULL则最小深度为left + right + 1;否则就正常看两边较小的深度 + 1。

时间O(n)

空间O(n) - worse case,如果树不平衡,比如node全是左子树或者右子树;平均空间是O(log(n))

Java实现

 1 class Solution {
 2     public int minDepth(TreeNode root) {
 3         if (root == null) {
 4             return 0;
 5         }
 6         int left = minDepth(root.left);
 7         int right = minDepth(root.right);
 8         if (left == 0 || right == 0) {
 9             return left + right + 1;
10         }
11         return Math.min(left, right) + 1;
12     }
13 }

JavaScript实现

 1 /**
 2  * @param {TreeNode} root
 3  * @return {number}
 4  */
 5 var minDepth = function (root) {
 6     if (root == null) {
 7         return 0;
 8     }
 9     let left = minDepth(root.left);
10     let right = minDepth(root.right);
11     if (left == 0 || right == 0) {
12         return left + right + 1;
13     }
14     return Math.min(left, right) + 1;
15 };

第二种思路是BFS。按照BFS的经典模板去遍历每一层的node。每弹出一个node的时候,判断当前node是否有左孩子和右孩子,如果没有,则说明当前这个node的深度应该是最小的了。

时间O(n)

空间O(n)

Java实现

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     public int minDepth(TreeNode root) {
12         // corner case
13         if (root == null) {
14             return 0;
15         }
16 
17         // normal case
18         Queue<TreeNode> queue = new LinkedList<>();
19         queue.offer(root);
20         int depth = 1;
21         while (!queue.isEmpty()) {
22             int size = queue.size();
23             for (int i = 0; i < size; i++) {
24                 TreeNode cur = queue.poll();
25                 if (cur.left == null && cur.right == null) {
26                     return depth;
27                 }
28                 if (cur.left != null) {
29                     queue.offer(cur.left);
30                 }
31                 if (cur.right != null) {
32                     queue.offer(cur.right);
33                 }
34             }
35             depth++;
36         }
37         return depth;
38     }
39 }

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/12515812.html