The Wayback Machine - https://web.archive.org/web/20241126224436/https://www.geeksforgeeks.org/minimum-time-required-to-infect-all-the-nodes-of-binary-tree/
Open In App

Minimum time required to infect all the nodes of Binary tree

Last Updated : 30 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a binary tree and a node start that is initially infected. For every second, neighbours of an infected node get infected. The task is to find the minimum time in which the whole tree will be infected.

Examples:

Input:
         10
      /     \
 12      13
        /       \
    14        15
   /  \        /   \
21 22  23  24
Start = 14
Output: 3

Input: 
       3
    /    \
  4      1
            \
             2
Start = 1
Output: 2

An approach using BFS (Breadth-first search):

The idea to solve this problem is by doing the BFS (breadth-first search) algorithm on the tree,  

Starts from the given special node “start”. During the BFS make all adjacent node infected. Keep counting the time in result, where we have visited all the node. 

One problem while infecting the adjacent node is that we can easily know the node’s children (left child or right child) which is adjacent but we can’t know that node’s parent directly. So, to overcome this problem we have to generate a parent-node relationship into some data structure, there we can keep track to node’s parent.

Follow the steps below to implement the above idea:

  • Store parent-child relations for each node in the parent array. (i.e, keeping track of the parent of any node)
  • Find the actual node “node” of a given special node start in the tree.
  • Create a queue for performing the BFS and an array visited to keep track of which node has already been infected.
  • Do BFS (Breadth-first search) by initially storing the “node” in the queue and making this “node” visited.
  • Do the following while queue size is greater than zero.
    • Iterate over the size of the queue and do the following:
      • Check if the current node’s parent exists in the tree and is not infected yet.
        • Push into the queue and make it visited to show it’s infected now.
      • Check if the current node’s left child exists in the tree and is not infected yet.
        • Push into the queue and make it visited to show it’s infected now.
      • Check if the current node’s right exists in the tree and is not infected yet.
        • Push into the queue and make it visited to show it’s infected now.
    • Increment the result by 1. (i.e, the infection has already spread by the above steps for this time.)
  • Return the result.

Below is the implementation of the above approach.

C++




// C++ code for the above approach:
 
#include <bits/stdc++.h>
using namespace std;
 
// A Tree node
struct Node {
    int val;
    struct Node *left, *right;
};
 
// Utility function to create a new node
Node* newNode(int val)
{
    Node* temp = new Node;
    temp->val = val;
    temp->left = temp->right = NULL;
    return (temp);
}
 
// "node" will store the actual Tree node
// of special node "start".
Node* node = NULL;
 
// Function for generating
// parent-root relationship
void findParent(Node* root, Node* p, vector<Node*>& parent,
                int start)
{
    if (root == NULL)
        return;
 
    // Store parent of current node
    parent[root->val] = p;
    if (root->val == start) {
        node = root;
    }
 
    findParent(root->left, root, parent, start);
    findParent(root->right, root, parent, start);
}
 
// Function to return the minimum amount
// of time require to infect all the
// nodes of binary tree
int amountOfTime(Node* root, int start)
{
 
    vector<Node*> parent(100005, NULL);
    findParent(root, NULL, parent, start);
 
    vector<bool> visited(100005, false);
 
    queue<Node*> q;
 
    // Push special tree node into the
    // queue and make it visited.
    q.push(node);
    visited[start] = true;
 
    // This store the minimum time require
    // to infect all the tree node.
    int result = -1;
 
    while (q.size() > 0) {
        int n = q.size();
 
        for (int i = 0; i < n; i++) {
            auto curr = q.front();
            int currNode = curr->val;
            q.pop();
 
            // Check if parent of currNode
            // exist and not visited yet
            // then push this parent of
            // current node into queue.
            if (parent[currNode] != NULL
                && visited[parent[currNode]->val]
                       == false) {
                visited[parent[currNode]->val] = true;
                q.push(parent[currNode]);
            }
 
            // Check if current node left
            // child exist and not
            // visited yet.
            if (curr->left
                && visited[curr->left->val] == false) {
                visited[curr->left->val] = true;
                q.push(curr->left);
            }
 
            // Check if current node right
            // child exist and not
            // visited yet.
            if (curr->right
                && visited[curr->right->val] == false) {
                visited[curr->right->val] = true;
                q.push(curr->right);
            }
        }
 
        // Increment the time
        result++;
    }
 
    // Return the result.
    return result;
}
 
// Driver Code
int main()
{
    /*      10
           /  \
          12  13
              / \
             14 15
            / \ / \
          21 22 23 24
 
        Let us create Binary Tree as shown
        above */
 
    Node* root = newNode(10);
    root->left = newNode(12);
    root->right = newNode(13);
 
    root->right->left = newNode(14);
    root->right->right = newNode(15);
 
    root->right->left->left = newNode(21);
    root->right->left->right = newNode(22);
    root->right->right->left = newNode(23);
    root->right->right->right = newNode(24);
 
    int start = 14;
 
    // Function call
    int result = amountOfTime(root, start);
    cout << result << endl;
 
    return 0;
}


Java




// Java code for the above approach
import java.io.*;
import java.util.*;
 
class Node {
  int val;
  Node left, right;
 
  public Node(int item)
  {
    val = item;
    left = right = null;
  }
}
 
class GFG {
  static Node node = null;
 
  // Function for generating
  // parent-root relationship
  static void findParent(Node root, Node p, Node[] parent,
                         int start)
  {
    if (root == null)
      return;
 
    // Store parent of current node
    parent[root.val] = p;
 
    if (root.val == start) {
      node = root;
    }
 
    findParent(root.left, root, parent, start);
    findParent(root.right, root, parent, start);
  }
 
  // Function to return the minimum amount
  // of time require to infect all the
  // nodes of binary tree
  static int amountOfTime(Node root, int start)
  {
 
    Node[] parent = new Node[100005];
    findParent(root, null, parent, start);
 
    boolean[] visited = new boolean[100005];
    Arrays.fill(visited, false);
 
    Queue<Node> q = new LinkedList<>();
 
    // add special tree node into the
    // queue and make it visited.
    q.add(node);
    visited[start] = true;
 
    // This store the minimum time require
    // to infect all the tree node.
    int result = -1;
 
    while (q.size() > 0) {
      int n = q.size();
 
      for (int i = 0; i < n; i++) {
        Node curr = q.peek();
        int currNode = curr.val;
        q.remove();
 
        // Check if parent of currNode
        // exist and not visited yet
        // then add this parent of
        // current node into queue.
        if (parent[currNode] != null
            && visited[parent[currNode].val]
            == false) {
          visited[parent[currNode].val] = true;
          q.add(parent[currNode]);
        }
 
        // Check if current node left
        // child exist and not
        // visited yet.
        if (curr.left!=null
            && visited[curr.left.val] == false) {
          visited[curr.left.val] = true;
          q.add(curr.left);
        }
 
        // Check if current node right
        // child exist and not
        // visited yet.
        if (curr.right!=null
            && visited[curr.right.val] == false) {
          visited[curr.right.val] = true;
          q.add(curr.right);
        }
      }
 
      // Increment the time
      result++;
    }
 
    // Return the result.
    return result;
  }
 
  public static void main(String[] args)
  {
    /*      10
           /  \
          12  13
              / \
             14 15
            / \ / \
          21 22 23 24
 
        Let us create Binary Tree as shown
        above */
 
    Node root = new Node(10);
    root.left = new Node(12);
    root.right = new Node(13);
 
    root.right.left = new Node(14);
    root.right.right = new Node(15);
 
    root.right.left.left = new Node(21);
    root.right.left.right = new Node(22);
    root.right.right.left = new Node(23);
    root.right.right.right = new Node(24);
 
    int start = 14;
 
    // Function call
    int result = amountOfTime(root, start);
    System.out.println(result);
  }
}
 
// This code is contributed by ishankhandelwals.


Python3




# Python program for the above approach
# A Tree node
class Node:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
 
# Utility function to create a new node
def newNode(val):
    return Node(val)
 
 
# "node" will store the actual Tree node
# of special node "start".
node = None
 
# Function for generating
# parent-root relationship
 
 
def findParent(root, p, parent, start):
    if not root:
        return
    # Store parent of current node
    parent[root.val] = p
    if root.val == start:
        global node
        node = root
    findParent(root.left, root, parent, start)
    findParent(root.right, root, parent, start)
 
# Function to return the minimum amount
# of time require to infect all the
# nodes of binary tree
 
 
def amountOfTime(root, start):
    parent = [None] * 100005
    findParent(root, None, parent, start)
 
    visited = [False] * 100005
 
    q = []
 
    # Push special tree node into the
    # queue and make it visited.
    q.append(node)
    visited[start] = True
 
    # This store the minimum time require
    # to infect all the tree node.
    result = -1
 
    while len(q) > 0:
        n = len(q)
        for i in range(n):
            curr = q.pop(0)
            currNode = curr.val
 
            # Check if parent of currNode
            # exist and not visited yet
            # then push this parent of
            # current node into queue.
            if parent[currNode] and not visited[parent[currNode].val]:
                visited[parent[currNode].val] = True
                q.append(parent[currNode])
 
            # Check if current node left
            # child exist and not
            # visited yet.
            if curr.left and not visited[curr.left.val]:
                visited[curr.left.val] = True
                q.append(curr.left)
 
            # Check if current node right
            # child exist and not
            # visited yet.
            if curr.right and not visited[curr.right.val]:
                visited[curr.right.val] = True
                q.append(curr.right)
 
        # Increment the time
        result += 1
 
    # Return the result.
    return result
 
 
# Driver Code
 
    """
      10
     /  \
    12  13
        / \
       14 15
      / \ / \
    21 22 23 24
 
    Let us create Binary Tree as shown
    above
    """
 
 
root = newNode(10)
root.left = newNode(12)
root.right = newNode(13)
 
root.right.left = newNode(14)
root.right.right = newNode(15)
 
root.right.left.left = newNode(21)
root.right.left.right = newNode(22)
root.right.right.left = newNode(23)
root.right.right.right = newNode(24)
 
start = 14
 
# Function call
result = amountOfTime(root, start)
print(result)
 
# This code is contributed by Potta Lokesh


C#




// C# code for the above approach:
using System;
using System.Collections.Generic;
 
public class Node {
  public int val;
  public Node left, right;
 
  public Node(int item)
  {
    val = item;
    left = right = null;
  }
}
 
public class GFG {
  // "node" will store the actual Tree node
  // of special node "start".
  public Node node;
 
  // Function for generating
  // parent-root relationship
  public void findParent(Node root, Node p, int[] parent,
                         int start)
  {
    if (root == null)
      return;
 
    // Store parent of current node
    parent[root.val] = p.val;
    if (root.val == start) {
      node = root;
    }
 
    findParent(root.left, root, parent, start);
    findParent(root.right, root, parent, start);
  }
 
  // Function to return the minimum amount
  // of time require to infect all the
  // nodes of binary tree
  public int amountOfTime(Node root, int start)
  {
    int[] parent = new int[100005];
    findParent(root, new Node(0), parent, start);
 
    bool[] visited = new bool[100005];
 
    Queue<Node> q = new Queue<Node>();
 
    // Push special tree node into the
    // queue and make it visited.
    q.Enqueue(node);
    visited[start] = true;
 
    // This store the minimum time require
    // to infect all the tree node.
    int result = -1;
 
    while (q.Count > 0) {
      int n = q.Count;
      for (int i = 0; i < n; i++) {
        var curr = q.Peek();
        int currNode = curr.val;
        q.Dequeue();
 
        // Check if parent of currNode
        // exist and not visited yet
        // then push this parent of
        // current node into queue.
        if (parent[currNode] != 0
            && visited[parent[currNode]] == false) {
          visited[parent[currNode]] = true;
          q.Enqueue(new Node(parent[currNode]));
        }
 
        // Check if current node left
        // child exist and not
        // visited yet.
        if (curr.left != null
            && visited[curr.left.val] == false) {
          visited[curr.left.val] = true;
          q.Enqueue(curr.left);
        }
 
        // Check if current node right
        // child exist and not
        // visited yet.
        if (curr.right != null
            && visited[curr.right.val] == false) {
          visited[curr.right.val] = true;
          q.Enqueue(curr.right);
        }
      }
      // Increment the time
      result++;
    }
 
    // Return the result.
    return result;
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    /*      10
               /  \
              12  13
                  / \
                 14 15
                / \ / \
              21 22 23 24
 
            Let us create Binary Tree as shown
            above */
 
    Node root = new Node(10);
    root.left = new Node(12);
    root.right = new Node(13);
 
    root.right.left = new Node(14);
    root.right.right = new Node(15);
 
    root.right.left.left = new Node(21);
    root.right.left.right = new Node(22);
    root.right.right.left = new Node(23);
    root.right.right.right = new Node(24);
 
    int start = 14;
 
    // Function call
    int result
      = new GFG().amountOfTime(root, start);
    Console.WriteLine(result);
  }
}
 
// This code is contributed by ishankhandelwals.


Javascript




// JS code
class Node
{
    constructor(item)
    {
        this.item = item;
        this.left = this.right = null;
    }
}
var node=null;
var item=null;
function findParent(root, p, parent,start)
{
if (root == null)
    return;
 
// Store parent of current node
parent[root.item] = p;
if (root.item == start) {
node = root;
}
 
findParent(root.left, root, parent, start);
findParent(root.right, root, parent, start);
}
 
 
function amountOfTime(root,start)
{
    let parent = new Array(100005);
    parent.fill(null);
 
    findParent(root, null, parent, start);
 
    let visited=new Array(100005);
    visited.fill(false);
 
    let q=[];
 
    // Push special tree node into the
    // queue and make it visited.
    q.push(node);
    visited[start] = true;
 
    // This store the minimum time require
    // to infect all the tree node.
    let result = -1;
 
    while (q.length > 0) {
        let n = q.length;
 
        for (let i = 0; i < n; i++) {
            let curr = q[0];
            let currNode = curr.item;
            q.shift();
 
            // Check if parent of currNode
            // exist and not visited yet
            // then push this parent of
            // current node into queue.
            if (parent[currNode] != null
                && visited[parent[currNode].item]
                       == false) {
                visited[parent[currNode].item] = true;
                q.push(parent[currNode]);
            }
 
            // Check if current node left
            // child exist and not
            // visited yet.
            if (curr.left
                && visited[curr.left.item] == false) {
                visited[curr.left.item] = true;
                q.push(curr.left);
            }
 
            // Check if current node right
            // child exist and not
            // visited yet.
            if (curr.right
                && visited[curr.right.item] == false) {
                visited[curr.right.item] = true;
                q.push(curr.right);
            }
        }
 
        // Increment the time
        result++;
    }
 
    // Return the result.
    return result;
}
 
 
// Driver Code
    /*      10
           /  \
          12  13
              / \
             14 15
            / \ / \
          21 22 23 24
 
        Let us create Binary Tree as shown
        above */
 
    let root = new Node(10);
    root.left = new Node(12);
    root.right = new Node(13);
 
    root.right.left = new Node(14);
    root.right.right = new Node(15);
 
    root.right.left.left = new Node(21);
    root.right.left.right = new Node(22);
    root.right.right.left = new Node(23);
    root.right.right.right = new Node(24);
 
    let start = 14;
 
    // Function call
    let result = amountOfTime(root, start);
    console.log(result);
     
    // This code is contributed by ishankhandlwals.


Output

3





Time Complexity: O(N), where N is the number of nodes in the binary tree.
Auxiliary Space: O(N)

Another method (Using Depth-first search (DFS))

The idea to solve this problem is by doing the  Depth-first search (DFS)  algorithm on the tree,

Algorithm

  • Create a function called “findParent” that takes a root node, a parent node pointer, a vector of Node pointers called “parent”, and an integer called “start”.
    • If the root node is NULL, return.
    • Store the parent of the current node in the “parent” vector at the index of the current node’s value.
    • If the current node’s value equals “start”, set the global “node” variable to the current node.
    • Recursively call the “findParent” function with the left and right children of the current node, passing in the current node as the parent node pointer.
  • Create a function called “amountOfTime” that takes a root node and an integer called “start”.
    • Create a “parent” vector of Node pointers with size 100005 and initialize all elements to NULL.
    • Call the “findParent” function with the root node, NULL as the parent node pointer, the “parent” vector, and the “start” integer.
    • Create a “visited” vector of bools with size 100005 and initialize all elements to false.
    • Declare an integer variable called “result” and initialize it to 0.
  • Define a lambda function called “dfs” that takes a Node pointer called “curr” and an integer called “dist”.
    • Mark the current node as visited in the “visited” vector.
    • Update the “result” variable to be the maximum of “result” and “dist”.
    • Traverse the current node’s left child, right child, and parent (if it exists) using a range-based for loop.
    • If a child or parent node is found and has not been visited before, recursively call the “dfs” function with the child/parent node and the updated distance.
    • Call the “dfs” function with the global “node” variable and 0 as the distance.
    • Return the “result” variable.

C++




#include <bits/stdc++.h>
using namespace std;
 
// A Tree node
struct Node {
    int val;
    struct Node *left, *right;
};
 
// Utility function to create a new node
Node* newNode(int val)
{
    Node* temp = new Node;
    temp->val = val;
    temp->left = temp->right = NULL;
    return (temp);
}
 
// "node" will store the actual Tree node
// of special node "start".
Node* node = NULL;
 
// Function for generating
// parent-root relationship
void findParent(Node* root, Node* p, vector<Node*>& parent,
                int start)
{
    if (root == NULL)
        return;
 
    // Store parent of current node
    parent[root->val] = p;
    if (root->val == start) {
        node = root;
    }
 
    findParent(root->left, root, parent, start);
    findParent(root->right, root, parent, start);
}
 
// Function to return the minimum amount
// of time require to infect all the
// nodes of binary tree
 int amountOfTime(Node* root, int start)
{
    vector<Node*> parent(100005, NULL);
    findParent(root, NULL, parent, start);
 
    vector<bool> visited(100005, false);
 
    int result = 0;
 
    function<void(Node*, int)> dfs = [&](Node* curr, int dist) {
        visited[curr->val] = true;
        result = max(result, dist);
        for (auto child : {curr->left, curr->right, parent[curr->val]}) {
            if (child && !visited[child->val]) {
                dfs(child, dist + 1);
            }
        }
    };
 
    dfs(node, 0);
 
    return result;
}
 
 
// Driver Code
int main()
{
    /*      10
           /  \
          12  13
              / \
             14 15
            / \ / \
          21 22 23 24
 
        Let us create Binary Tree as shown
        above */
 
    Node* root = newNode(10);
    root->left = newNode(12);
    root->right = newNode(13);
 
    root->right->left = newNode(14);
    root->right->right = newNode(15);
 
    root->right->left->left = newNode(21);
    root->right->left->right = newNode(22);
    root->right->right->left = newNode(23);
    root->right->right->right = newNode(24);
 
    int start = 14;
 
    // Function call
    int result = amountOfTime(root, start);
    cout << result << endl;
 
    return 0;
}


Java




import java.util.ArrayList;
import java.util.List;
 
// A Tree node
class Node {
    int val;
    Node left, right;
    // Utility function to create a new node
    Node(int val) {
        this.val = val;
        this.left = this.right = null;
    }
}
public class GFG {
 
    // "node" will store the actual Tree node of the special node "start".
    static Node node = null;
    // Function for generating parent-root relationship
    static void findParent(Node root, Node p, List<Node> parent, int start) {
        if (root == null)
            return;
        // Store the parent of the current node
        parent.set(root.val, p);
        if (root.val == start) {
            node = root;
        }
        findParent(root.left, root, parent, start);
        findParent(root.right, root, parent, start);
    }
    // Function to return the minimum amount
    // of time required to infect all the nodes of the binary tree
    static int amountOfTime(Node root, int start) {
        List<Node> parent = new ArrayList<>();
        for (int i = 0; i < 100005; i++) {
            parent.add(null);
        }
        findParent(root, null, parent, start);
        boolean[] visited = new boolean[100005];
        int[] result = { 0 };
        // Depth-First Search (DFS) function
        // to traverse the binary tree     
        dfs(node, 0, visited, parent, result);
        return result[0];
    }
    static void dfs(Node curr, int dist, boolean[] visited, List<Node> parent, int[] result) {
        visited[curr.val] = true;
        result[0] = Math.max(result[0], dist);
        for (Node child : new Node[] { curr.left, curr.right, parent.get(curr.val) }) {
            if (child != null && !visited[child.val]) {
                dfs(child, dist + 1, visited, parent, result);
            }
        }
    }
    // Driver Code
    public static void main(String[] args) {
        Node root = new Node(10);
        root.left = new Node(12);
        root.right = new Node(13);
        root.right.left = new Node(14);
        root.right.right = new Node(15);
        root.right.left.left = new Node(21);
        root.right.left.right = new Node(22);
        root.right.right.left = new Node(23);
        root.right.right.right = new Node(24);
        int start = 14;
        // Function call
        int result = amountOfTime(root, start);
        System.out.println(result);
    }
}


Python3




# A Tree node
class Node:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None
 
#  Utility function to create a new node
def newNode(val):
    temp = Node(val)
    #temp.val =
    temp.left = None
    temp.right = None
    return temp
 
# "node" will store the actual Tree node
# of special node "start".
node = None
 
# Function for generating
# parent-root relationship
def findParent(root, p, parent, start):
    if root is None:
        return
    # Store parent of current node
    parent[root.val] = p
    if root.val == start:
        global node
        node = root
    findParent(root.left, root, parent, start)
    findParent(root.right, root, parent, start)
# Function to return the minimum amount
# of time require to infect all the
# nodes of binary tree
def amountOfTime(root, start):
    parent = [None] * 100005
    findParent(root, None, parent, start)
    visited = [False] * 100005
    result = 0
    def dfs(curr, dist):
        nonlocal result
        visited[curr.val] = True
        result = max(result, dist)
        for child in [curr.left, curr.right, parent[curr.val]]:
            if child and not visited[child.val]:
                dfs(child, dist + 1)
    dfs(node, 0)
    return result
 
# Driver Code
root = newNode(10)
root.left = newNode(12)
root.right = newNode(13)
root.right.left = newNode(14)
root.right.right = newNode(15)
root.right.left.left = newNode(21)
root.right.left.right = newNode(22)
root.right.right.left = newNode(23)
root.right.right.right = newNode(24)
start = 14
 
result = amountOfTime(root, start)
print(result)


C#




using System;
using System.Collections.Generic;
 
// A Tree node
public class Node
{
    public int val;
    public Node left, right;
 
    // Utility function to create a new node
    public Node(int val)
    {
        this.val = val;
        this.left = this.right = null;
    }
}
 
public class MinTimeToInfect
{
    // "node" will store the actual Tree node
    // of the special node "start".
    static Node node = null;
 
    // Function for generating
    // parent-root relationship
    static void FindParent(Node root, Node p, List<Node> parent, int start)
    {
        if (root == null)
            return;
 
        // Store parent of current node
        parent[root.val] = p;
        if (root.val == start)
        {
            node = root;
        }
 
        FindParent(root.left, root, parent, start);
        FindParent(root.right, root, parent, start);
    }
 
    // Function to return the minimum amount
    // of time required to infect all the
    // nodes of the binary tree
    static int AmountOfTime(Node root, int start)
    {
        List<Node> parent = new List<Node>(100005);
        for (int i = 0; i < 100005; i++)
        {
            parent.Add(null);
        }
 
        FindParent(root, null, parent, start);
 
        bool[] visited = new bool[100005];
        int[] result = new int[] { 0 };
 
        // DFS function
        // It is declared here to access the `result` variable
        Action<Node, int> dfs = null;
        dfs = (curr, dist) =>
        {
            visited[curr.val] = true;
            result[0] = Math.Max(result[0], dist);
            foreach (var child in new Node[] { curr.left, curr.right, parent[curr.val] })
            {
                if (child != null && !visited[child.val])
                {
                    dfs(child, dist + 1);
                }
            }
        };
 
        dfs(node, 0);
 
        return result[0];
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        /*      10
               /  \
              12  13
                  / \
                 14 15
                / \ / \
              21 22 23 24
 
            Let us create Binary Tree as shown
            above */
 
        Node root = new Node(10);
        root.left = new Node(12);
        root.right = new Node(13);
 
        root.right.left = new Node(14);
        root.right.right = new Node(15);
 
        root.right.left.left = new Node(21);
        root.right.left.right = new Node(22);
        root.right.right.left = new Node(23);
        root.right.right.right = new Node(24);
 
        int start = 14;
 
        // Function call
        int result = AmountOfTime(root, start);
        Console.WriteLine(result);
    }
}


Javascript




class GFG {
    constructor(val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}
// A global variable to store the
// special node
let node = null;
// Function to find the
// parent-root relationship
function findParent(root, p, parent, start) {
    if (root === null) return;
    parent[root.val] = p;
    if (root.val === start) {
        node = root;
    }
    findParent(root.left, root, parent, start);
    findParent(root.right, root, parent, start);
}
// Function to return the minimum amount of time
function amountOfTime(root, start) {
    const parent = Array(100005).fill(null);
    findParent(root, null, parent, start);
    const visited = Array(100005).fill(false);
    let result = 0;
    function dfs(curr, dist) {
        visited[curr.val] = true;
        result = Math.max(result, dist);
        for (const child of [curr.left, curr.right, parent[curr.val]]) {
            if (child && !visited[child.val]) {
                dfs(child, dist + 1);
            }
        }
    }
    dfs(node, 0);
    return result;
}
// Driver Code
(function main() {
    /*      10
           /  \
          12  13
              / \
             14 15
            / \ / \
          21 22 23 24
    */
    const root = new GFG(10);
    root.left = new GFG(12);
    root.right = new GFG(13);
    root.right.left = new GFG(14);
    root.right.right = new GFG(15);
    root.right.left.left = new GFG(21);
    root.right.left.right = new GFG(22);
    root.right.right.left = new GFG(23);
    root.right.right.right = new GFG(24);
    const start = 14;
    // Function call
    const result = amountOfTime(root, start);
    console.log(result);
})();


Output

3





Time complexity: O(N),where N is the number of nodes in the binary tree, as it visits each node once.  
Space complexity:  O(N),because it uses a vector of Node pointers called “parent” with size 100005 to store the parent nodes of each node in the binary tree.



Previous Article
Next Article

Similar Reads

Minimum hours taken by Zombies to infect all Humans by infecting up, left, down and right only
Given a 2D grid, each cell is either a zombie 1 or human 0. Zombies can turn adjacent horizont or vertical (up/down/left/right) human beings into zombies every hour. The task is to find out how many hours it will take to infect all humans. Examples: Input: arr[][] = { { 0, 1, 0, 1 }, { 0, 0, 0, 0 }, { 0, 0, 0, 1 } };Output: 3Explanation: In time =
13 min read
Minimum time required to visit all the special nodes of a Tree
Given an undirected tree consisting of N vertices where some of the nodes are special nodes, the task is to visit all the special nodes from the root node in minimum time. Time for traveling from one node to another node can be assumed as unit time. A node is special if the path from the root to the node consists of distinct value nodes. Example: I
14 min read
Minimum number of cameras required to monitor all nodes of a Binary Tree
Given a Binary Tree consisting of N nodes, the task is to find the minimum number of cameras required to monitor the entire tree such that every camera placed at any node can monitor the node itself, its parent, and its immediate children. Examples: Input: 0 / 0 /\ 0 0Output: 1Explanation: 0 / 0 <---------- Camera / \ 0 0In the above tree, the n
8 min read
Minimum swap required to convert binary tree to binary search tree
Given an array arr[] which represents a Complete Binary Tree i.e., if index i is the parent, index 2*i + 1 is the left child and index 2*i + 2 is the right child. The task is to find the minimum number of swaps required to convert it into a Binary Search Tree. Examples: Input: arr[] = [5, 6, 7, 8, 9, 10, 11]Output: 3Explanation:Binary tree of the g
9 min read
Minimum number of nodes to be selected to light up all the edges of the tree (Select Nodes)
Given N nodes of a tree and a list of edges. Find the minimum number of nodes to be selected to light up all the edges of the tree. An edge lights up when at least one node at the end of the edge is selected. Example: Input: N = 6, edges[] = {(1,2), (1,3), (2,4), (3,5), (3,6)}Output: 2Explanation: Selecting nodes 2 and 3 lights up all the edges. In
10 min read
Total time to visit all nodes of a binary tree
Given a binary tree, find the total time to visit all nodes from the root node. Visiting a child node from its parent node will cost 1 unit of time and visiting the parent from the child node will cause 0 units of time. Examples: Input: Output: 5Explanation: The traversals taking 1 unit of time are 1->2, 2->4, 4->5, 1->3 and 3->6. In
5 min read
Minimum time required to color all edges of a Tree
Given an array of pairs Edges[][], representing edges connecting vertices in a Tree consisting of N nodes, the task is to find the minimum time required to color all the edges of a Tree based on the assumption that coloring an edge requires 1 unit of time. Note: Multiple edges can be colored on a particular instant, but a node can be part of only o
7 min read
Convert given Binary Tree to Symmetric Tree by adding minimum number of nodes
Given a Binary Tree, the task is to convert the given Binary Tree to the Symmetric Tree by adding the minimum number of nodes in the given Tree. Examples: Input: Output: Input: Output: Approach: To solve this problem, follow the below steps: Make a function buildSymmetricTree which will accept two parameters root1 and root2.Here, root1 and root2, a
8 min read
Find a set of at most N/2 nodes from a Graph such that all remaining nodes are directly connected to one of the chosen nodes
Given an integer N, representing the number of nodes present in an undirected graph, with each node valued from 1 to N, and a 2D array Edges[][], representing the pair of vertices connected by an edge, the task is to find a set of at most N/2 nodes such that nodes that are not present in the set, are connected adjacent to any one of the nodes prese
12 min read
Minimum Time Required to Visit Each Disappearing Nodes
Given an undirected graph with n nodes that are represented by a 2D array edges where edges[i] = [ui, vi, timei] describes an edge between nodes ui and vi with a traversal time of timei. Additionally, you are given an array disappear[], where disappear[i] denotes the time when node i becomes unavailable. The graph may be disconnected and contain mu
6 min read
Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
Given a tree, and the weights (in the form of strings) of all the nodes, the task is to count the nodes whose weighted string when concatenated with the strings of the sub-tree nodes becomes a pangram. Pangram: A pangram is a sentence containing every letter of the English Alphabet. Examples: Input: Output: 1 Only the weighted string of sub-tree of
7 min read
Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree
Given a Binary Tree, the task is for each level is to print the total number of nodes from all lower levels which are less than or equal to every node present at that level. Examples: Input: Below is the given tree: 4 / \ 3 5 / \ / \ 10 2 3 1 Output: 4 3 0Explanation:Nodes in level 1 has 4 nodes as (3) in level 2 and (2, 3, 1) in level 3. Nodes in
11 min read
Count of leaf nodes required to be removed at each step to empty a given Binary Tree
Given a Binary Tree, the task is to remove the leaf nodes of the Binary Tree during each operation and print the count. Examples: Input: Output: 4 2 1 1 Explanation: In the 1st operation removing the leaf nodes { 1, 3, 4, 6 } from the binary tree. In the 2nd operation removing the leaf nodes { 8, 7 } In the 3rd operation removing the leaf nodes { 5
9 min read
Sum of nodes in a binary tree having only the left child nodes
Given a binary tree, the task is to find the sum of binary tree nodes having only the left child nodes. Example: Input: 8 / \ 3 7 / \ / 5 6 0 / / 1 2Output: 18 Explanation: Nodes with values 5, 6, and 7 are the ones that have only the left child nodes Input: 2 / \ 3 1 / / 5 6Output: 4 Approach: The given problem can be solved by traversing the bina
6 min read
Count of nodes in a binary tree having their nodes in range [L, R]
Given a Binary Tree consisting of n nodes and two positive integers l and r, the task is to find the count of nodes having their value in the range [l, r]. Examples: Input: l = 4, r = 15 Output: 4Explanation: The nodes in the given Tree that lies in the range [4, 15] are {4, 5, 6, 7}. Input: l = 1, r = 8 Output: 2Explanation: The nodes in the given
10 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Count of all prime weight nodes between given nodes in the given Tree
Given a weighted tree containing N nodes, and two nodes u and v, the task is to find the count of nodes having prime weight on the simple path between u and v (both inclusive). Examples: Input: u = 3, v = 5 Output: 2 Explanation: Prime weight on path 3 to 5 is [11, 5]. Hence, the answer is 2. Approach: To solve the problem mentioned above, the idea
15 min read
Construct a Tree whose sum of nodes of all the root to leaf path is not divisible by the count of nodes in that path
Given an N-ary tree consisting of N nodes numbered from 1 to N rooted at node 1, the task is to assign values to each node of the tree such that the sum of values from any root to the leaf path which contains at least two nodes is not divisible by the number of nodes along that path. Examples: Input: N = 11, edges[][] = {{1, 2}, {1, 3}, {1, 4}, {1,
11 min read
Count of nodes in a given N-ary tree having distance to all leaf nodes equal in their subtree
Given an N-ary tree root, the task is to find the number of non-leaf nodes in the tree such that all the leaf nodes in the subtree of the current node are at an equal distance from the current node. Example: Input: Tree in the below imageOutput: 4Explanation: The nodes {10, 3, 2, 4} have the distance between them and all the leaf nodes in their sub
11 min read
Minimum operations required to convert a binary string to all 0s or all 1s
Given a binary string str, the task is to find the minimum number of operations required to make all the characters of the string same i.e. either the resultant string contains all 0s or all 1s. In a single operation, any block of consecutive 0s can be converted to a block of consecutive 1s of the same length and vice versa. Examples: Input: str =
4 min read
Minimum time required to cover a Binary Array
Given an integer N which represents the size of a boolean array that is initially filled with 0, and also given an array arr[] of size K consisting of (1-based) indices at which '1' are present in the boolean array. Now, at one unit of time the adjacent cells of the arr[i] in the boolean array become 1 that is 010 becomes 111. Find the minimum time
8 min read
Construct XOR tree by Given leaf nodes of Perfect Binary Tree
Given the leaf nodes of a perfect binary tree, the task is to construct the XOR tree and print the root node of this tree. An XOR tree is a tree whose parent node is the XOR of the left child and the right child node of the tree. Parent node = Left child node ^ Right child node Examples: Input: arr = {40, 32, 12, 1, 4, 3, 2, 7} Output: Nodes of the
12 min read
Count of nodes in given N-ary tree such that their subtree is a Binary Tree
Given an N-ary tree root, the task is to find the count of nodes such that their subtree is a binary tree. Example: Input: Tree in the image below Output: 11Explanation: The nodes such that there subtree is a binary tree are {2, 8, 10, 6, 7, 3, 1, 9, 5, 11, 12}. Input: Tree in the image below Output: 9 Approach: The given problem can be solved by u
11 min read
Minimum difference between any two weighted nodes in Sum Tree of the given Tree
Given a tree of N nodes, the task is to convert the given tree to its Sum Tree(including its own weight) and find the minimum difference between any two node's weight of the sum tree. Note: The N nodes of the given tree are given in the form of top to bottom with N-1 line where each line describes two nodes that are connected. Examples: Input: Outp
11 min read
Minimum time required to complete all tasks with alteration of their order allowed
Given a string S consisting of N characters (representing the tasks to perform) and a positive integer K, the task is to find the minimum time required to complete all the given tasks in any order, given that each task takes one unit of time and each task of the same type must be performed at an interval of K units. Examples: Input: S = "AAABBB", K
8 min read
Minimum time required to transport all the boxes from source to the destination under the given constraints
Given two arrays, box[] and truck[], where box[i] represents the weight of the ith box and truck[i] represents the maximum load that the ith truck can carry. Now each truck takes 1 hour to transport a box from source to destination and another one hour to come back. Now, given that all the boxes are kept at the source, the task is to find the minim
10 min read
Minimum time required to rot all oranges | Dynamic Programming
Given a matrix of dimension m * n where each cell in the matrix can have values 0, 1, or 2 which has the following meaning: 0: Empty cell 1: Cells have fresh oranges 2: Cells have rotten oranges So the task is to determine what is the minimum time required so that all the oranges become rotten. A rotten orange at index [i, j] can rot other fresh or
15 min read
Minimum time required by n cars to travel through all of the m roads
Given m roads and n cars. The cars are numbered from 1 to n. You are also given an array arr[] of size m, each road has a value arr[i] - the index of a car that runs fast on this road. If a car is fast on a road, then it travels across the road in 1 hour, else it takes 2 hours (if not proficient) to travel through this road. Find out the minimum ti
13 min read
Minimum time required to complete all tasks without altering their order
Given a string S consisting of N characters (representing the tasks to perform) and a positive integer K, the task is to find the minimum time required to complete all the given tasks in the given order such that each task takes one unit of time and each task of the same type must be performed at an interval of K units. Examples: Input: S = "ABACCA
6 min read
Minimum time to visit all nodes of given Graph at least once
Given a graph and the list of neighbours for each node in an array graph[] of size N, where graph[i] contains a list of neighbor nodes that are connected to ith node, the task is to visit all the nodes of the given graph in a minimum amount of time. Note: Movement from any node to its neighbour takes one unit of time Example: Input: [[1, 2, 3], [2,
12 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg