题目

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.

大致意思

给你一个二叉树,查找他存在的最短路径

解决方案

  • 进行遍历,每次遍历,level + 1,直到这个节点的左子树和右子树都不存在的时候,记录这个点的level
  • 再根据min进行判断,如果min > level,则进行替换

源代码

var minDepth = function(root) {
   if (!root) return 0;
   var min = 999999999;
   search(root, 1);

   function search(root, level) {
     if (root) {
       if (!root.left && !root.right) {
         if (min > level) min = level;
       }
       search(root.left, level + 1);
       search(root.right, level + 1);
     }
   }

   return min;
 };