题目: 给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。 题目链接
我的JavaScript解法
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var minDepth = function(root) {
if(root == null) return 0;
let stack = [];
stack.push(root);
let depth = 1;
while(stack.length) {
let len = stack.length;
for(let i = 0; i < len; i++) {
const current = stack.shift();
if(current.left == null && current.right == null)
return depth;
if(current.left != null)
stack.push(current.left);
if(current.right != null)
stack.push(current.right);
}
depth++;
}
return depth;
};