Closest Leaf in a Binary Tree
Description
null
Solution(javascript)
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {number} k
* @return {number}
*/
const findClosestLeaf = function (root, k) {
const adj = {}
const set = (nodeA, nodeB) => {
const a = nodeA.val
const b = nodeB.val
adj[a] = adj[a] || []
adj[a].push(nodeB)
adj[b] = adj[b] || []
adj[b].push(nodeA)
}
let source = null
const aux = (node) => {
if (node.left) {
set(node, node.left)
aux(node.left)
}
if (node.val === k) {
source = node
}
if (node.right) {
set(node, node.right)
aux(node.right)
}
}
aux(root)
let current = [source]
const visited = {
[k]: true,
}
while (current.length) {
const next = []
for (const node of current) {
if (!node.left && !node.right) {
return node.val
}
adj[node.val].forEach((nextNode) => {
if (!visited[nextNode.val]) {
visited[nextNode.val] = true
next.push(nextNode)
}
})
}
current = next
}
return -1
}