Skip to main content

2385.js

class TreeNode {
constructor(val = 0, left = null, right = null) {
this.val = val
this.left = left
this.right = right
}
}

const buildTree = (array, index = 0) => {
if (index < array.length && array[index] != null) {
let node = new TreeNode(arr[index])
node.left = buildTree(array, 2 * index + 1)
node.right = buildTree(array, 2 * index + 2)

return node
}

return null
}

/** ------------------------------------------------------------------------------
*
* 2385. Amount of Time for Binary Tree to Be Infected
* Topics: Hash Table, DFS
* https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected/description/
*
------------------------------------------------------------------------------ */
/**
* 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
* @param {number} start
* @return {number}
*/
var amountOfTime = function (root, start) {
const graph = createGraph(root, {})

console.log(graph)
}

let rootArray = [1, 5, 3, null, 4, 10, 6, 9, 2]
let start = 3

let root = buildTree(rootArray)
console.log(root, start)

const createGraph = (node, graph) => {
if (!node) return graph

if (!(node.val in graph)) graph[node.val] = []

if (node.left) {
graph[node.val].push(node.left.val)
if (!node.left.val in graph) graph[node.left.val] = []
graph[node.left.val].push(node.val)
createGraph(node.left, graph)
}

if (node.right) {
graph[node.val].push(node.right.val)
if (!(node.right.val in graph)) graph[node.right.val] = []
graph[node.right.val].push(node.val)
createGraph(node.right, graph)
}
return graph
}