Minimum Depth of Binary Tree
Given the root of a binary tree, return its minimum depth: the number of nodes on the shortest path from the root down to the nearest leaf.
A leaf is a node with no children. A node that has only one child is not a leaf, so a path can't stop there.
An empty tree has minimum depth 0.
Constraints
- The tree has between
0and10^5nodes. -1000 <= Node.val <= 1000
Examples
Example 1
Input: root = [3,5,8,null,null,2,6] Output: 2
5 is a leaf on level 2, so the shortest root-to-leaf path is 3 → 5: 2 nodes.
Example 2
Input: root = [1,null,2,null,3,null,4] Output: 4
The root has only a right child, so it is not a leaf. The only leaf is 4, at depth 4.
Example 3
Input: root = [] Output: 0
An empty tree has depth 0.
JavaScript you'll use: Stacks, queues and deques Linked list and tree nodes
/**
* Tree nodes are provided (you don't need to define them):
* class TreeNode { constructor(val = 0, left = null, right = null) { this.val = val; this.left = left; this.right = right; } }
*/
/**
* @param {TreeNode | null} root
* @return {number}
*/
function minDepth(root) {
}
Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.