思路
广度优先遍历,在遍历过程中遇到叶子节点停止遍历返回层级
代码
/**
* 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) {
const bfs = (n) => {
if(n){
//新建一个队列,根节点入队
const q = [[root,1]]
while(q.length){
//根节点出对后,左右节点挨个入队
const [a,l] = q.shift()
if(!a.left && !a.right){
return l
}
if(a.left) q.push([a.left,l+1])
if(a.right) q.push([a.right,l+1])
}
}
return 0;
}
return bfs(root)
};
复杂度
时间:O(n)
空间:O(n)