Reputation: 11
trying to convert a level order input to a N-Ary tree. Where levels are separated by a null. Example. Input: [1, null, 2,3,4, null,5,6,null,7,8,null,9,10] Code is expected to build a tree and finally print the preorder of the same for validation.
Output: [1,2,5,6, 3,7,8,4,9,10]
Not getting the desired output. Also this needs to be solved iteratively and recursion may not be used. Below is the full code. Added some print statement to ease debugging.
enter code here
package AllTree;
import java.util.*;
public class ListToNArrayTree {
public static class Node{
public int val;
public ArrayList<Node> children = new ArrayList<>();
public Node (int val){
this.val = val;
}
public Node (int val, ArrayList<Node> children){
this.val = val;
this.children = children;
}
public String toString(){
return " " + val;
}
public ArrayList<Node> getChildren() {
return children;
}
public void setChildren(ArrayList<Node> children) {
this.children = children;
}
}
public static Node buildTree(List<Integer> dataAsList){
/*Check if the input is valid to create a tree example {1, null, 2,3,4, null,5,6,null,7,8,null,9,10, null};
Above is a level order so null is mandatory @ position 1.
*/
if (dataAsList.isEmpty() || dataAsList.get(0) == null|| dataAsList.get(1) !=null){
System.out.println ("Invalid data to construct a tree");
return null;
}
/*Create queue to hold all values from input*/
Queue<Integer> dataAsQueue = new LinkedList<>();
for (Integer data: dataAsList) {
dataAsQueue.add(data);
}
/*Create queue to hold the nodes which will be retrieved in FIFO to add corresponding children*/
Queue<Node> dataAsTree = new LinkedList<>();
Node root = new Node(dataAsQueue.poll()); // to poll the root element
dataAsQueue.poll(); // to poll the null - as after this is the beginning of the second level of the tree
dataAsTree.add(root);
root = dataAsTree.poll();
Node parent = root;
while (!dataAsQueue.isEmpty()) {
Node parent_ = parent;
Integer childInt= dataAsQueue.poll();
if (childInt != null){
parent_.getChildren().add(new Node(childInt));
dataAsTree.add(new Node(childInt));
}
else{
parent = dataAsTree.poll();
}
System.out.println ("Current parent " + parent_ + " with children" + parent_.children);
}
return root;
}
public static void main(String[] args){
List<Integer> dataAsList = Arrays.asList(1, null, 2,3,4, null,5,6,null,7,8,null,9,10);
// Node root = buildTree(dataAsList);
System.out.println ("PreOrder Sorting" + preorder( buildTree(dataAsList)));
}
public static List<Integer> preorder(Node root) {
LinkedList<Integer> res = new LinkedList<>();
if (root == null) {
return res;
}
preorderhelper(root, res);
return res;
}
private static void preorderhelper(Node root, LinkedList<Integer> res) {
if (root == null) {
return;
}
res.add(root.val);
if (root.children != null) {
for (Node c : root.children) {
preorderhelper(c, res);
}
}
}
}
Upvotes: 1
Views: 37