This is Discussion thread about Construct Parent array Tree
Discussion About Construct Parent array Tree
when i am complie code its gives InputMismatchException but inputFormate is correct i dont know why this compliation error come.
////////////////////////////////////////////////////////////////
import java.util.*;
class TreeNode {
int data;
TreeNode left;
TreeNode right;
TreeNode(int data) {
this.data = data;
}
}
public class Main {
public static void constractTree(int[] nums) {
Queue<TreeNode> queue = new LinkedList<>();
Map<Integer, ArrayList<Integer>> nodeTrack = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (nodeTrack.containsKey(nums[i])) {
ArrayList<Integer> nodes = nodeTrack.get(nums[i]);
nodes.add(i);
} else {
ArrayList<Integer> nodes = new ArrayList<>();
nodes.add(i);
nodeTrack.put(nums[i], nodes);
}
}
TreeNode rootNode = null;
if (nodeTrack.containsKey(-1)) {
ArrayList<Integer> rootList = nodeTrack.get(-1);
Integer rootData = rootList.get(0);
TreeNode root = new TreeNode(rootData);
queue.add(root);
}
while (!queue.isEmpty()) {
TreeNode root = queue.poll();
if (rootNode == null) {
rootNode = root;
}
if (nodeTrack.containsKey(root.data)) {
ArrayList<Integer> nodeList = nodeTrack.get(root.data);
Integer leftData = nodeList.get(0);
if (nodeList.size() == 2) {
Integer rightChild = nodeList.get(1);
TreeNode leftNode = new TreeNode(leftData);
TreeNode rightNode = new TreeNode(rightChild);
root.left = leftNode;
root.right = rightNode;
queue.add(leftNode);
queue.add(rightNode);
} else {
TreeNode leftNode = new TreeNode(leftData);
root.left = leftNode;
queue.add(leftNode);
}
}
}
preOrder(rootNode);
}
private static void preOrder(TreeNode root) {
if (root == null) {
return;
}
System.out.print(root.data + " ");
preOrder(root.left);
preOrder(root.right);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int testcase = scanner.nextInt();
scanner.nextLine();
for (int i = 0; i < testcase; i++) {
int n = scanner.nextInt();
int[] arrayTree = new int[n];
for (int j = 0; j < arrayTree.length; j++) {
arrayTree[j] = scanner.nextInt();
}
constractTree(arrayTree);
}
}
}