题目链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
思路:BFS(广度优先搜索),在遍历的时候,会增加每个节点的level信息,然后把每个「叶子节点」的level数都丢到一个min数组中,最后从min数组中找到最小的数返回。
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var minDepth = function(root) {
if(root === null) return 0;
let stack = [];
let level = 1;
let min = [];
stack.push([level, root]);
while(stack.length > 0) {
let pop = stack.pop();
let node = pop[1];
level = pop[0];
if(node.left === null && node.right == null) {
min.push(level);
} else {
if(node.left != null || node.right !== null) {
level += 1;
}
if(node.left != null) {
stack.push([level, node.left]);
}
if(node.right != null) {
stack.push([level, node.right]);
}
}
}
return Math.min(...min);
};
网友评论