Thursday, February 24, 2022

Display A Generic Tree

I/P: { 10, 20, 40, -1, -1, 30, 50, -1, 60}

O/P:

10 -> 20, 30, .

20 -> 40, .

40 -> .

30 -> 50, 60, .

50 -> .

60 -> .





package pep.Day28;

import java.util.ArrayList;
import java.util.Stack;

public class Display_Generic_Tree {
private static class Node {
int data;
ArrayList<Node> children = new ArrayList<>();
}

public static void main(String[] args) {
int[] arr = new int[]{10, 20, 40, -1, -1, 30, 50, -1, 60};

Node root = null;
Stack<Node> stack = new Stack<>();
for (int i = 0; i < arr.length; i++) {
if (arr[i] == -1)
stack.pop();
else {
Node child = new Node();
child.data = arr[i];
if (!stack.isEmpty()) {
stack.peek().children.add(child);
} else {
root = child;
}
stack.push(child);

}
}

System.out.println(root);
display(root);
}

// Expectation -> d(10): 10 will print itself and its family
// FAITH -> d(20), d(30): will print itself and its family
// d(10) = self(10) + d(20)+ d(30)
private static void display(Node root) {
// self(10)
String str = root.data + " -> ";
for (Node child : root.children) {
str += child.data + ", ";
}
str += ".";
System.out.println(str);

// d(20)+ d(30)
for (Node child : root.children) {
display(child);
}

}
}



Time Complexity:

We are traversing the entire tree once, i.e. we are making a recursive call for the display of each 

node, hence the total time complexity is O(n) where n = number of nodes in the generic tree.



Space Complexity:

We are not taking any auxiliary data structure, hence the extra space used is O(1). However, we are using recursion, which does take recursion called stack space. The recursion can grow to the maximum depth of the tree. Hence, the recursive stack will take O(d) space where d = depth of the tree. Note: In the worst case, the depth of the tree can be equal to the number of nodes in the tree, if all nodes are linearly arranged. Hence, the recursion call stack can take O(n) space in the worst case. 


No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...