[LeetCode] 111. Minimum Depth of Binary Tree

二叉树的最小深度。题目即是题意。例子,

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 };

 

你可能感兴趣的:([LeetCode] 111. Minimum Depth of Binary Tree)