Topic describes
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node to the nearest leaf node.
Note: Leaf nodes are nodes that have no child nodes.
/** * 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) * } */
/** Solution steps: 1, breadth-first traversal of the whole tree, and record the level 2 of each node. When a leaf node is encountered, return to the node level, stop traversal 3, and follow my wechat public account to get more content: hand touch hand front end advanced */
/ * * *@param {TreeNode} root
* @return {number}* /
var minDepth = function(root) {
if(! root)return 0
const q = [[root, 1]]
while(q.length) {
const [n, levl] = q.shift()
if(! n.left && ! n.right) {return levl
}
if(n.left) q.push([n.left, levl + 1])
if(n.right) q.push([n.right, levl + 1])}};// The title is reprinted from licou official website:
// https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
Copy the code