#2385. Amount of Time for Binary Tree to Be Infected

ยท

1 min read

https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected/?envType=daily-question&envId=2024-01-10

 function amountOfTime(root, start) {
      const treeMap = {}
      convert(root, 0, treeMap)
      const queue = [start]
      let minute = 0
      const visited = new Set([start])

      while (queue.length > 0) {
        const levelSize = queue.length
        for (let i = 0; i < levelSize; i++) {
          const current = queue.shift()
          for (const num of treeMap[current] || []) {
            if (!visited.has(num)) {
              visited.add(num)
              queue.push(num)
            }
          }
        }
        minute += 1
      }

      return minute - 1
    }

    function convert(current, parent, treeMap) {
      if (current === null) {
        return
      }
      if (!treeMap[current.val]) {
        treeMap[current.val] = new Set()
      }
      const adjacentList = treeMap[current.val]
      if (parent !== 0) {
        adjacentList.add(parent)
      }
      if (current.left) {
        adjacentList.add(current.left.val)
      }
      if (current.right) {
        adjacentList.add(current.right.val)
      }
      convert(current.left, current.val, treeMap)
      convert(current.right, current.val, treeMap)
    }

On seeing this question, I knew Breadth First Search would solve it. What I didn't know was that it had to be converted to an undirected graph, this is because Binary Tree (a type of graph) is directed, and the child node cannot point to the parent but they can if it's an undirected graph.

So the convert method turns the binary tree to an undirected graph and the amountOfTime method runs a breadth first search on each node and their children, then get the total time taken to infect the all tree.

I need to study more on graph.

ย