I would like to display the level of the tree structure by level. My current code traverses BFS or Level Order Traversal, but I cannot get output to display a tree structure such as a tree. See Current Output and Expected Result.
My idea was to use some sort of counting to iterate over elements from one level in the queue.
How can i do this.
The source code without this function can be found in the link below, if someone needs the entire else implementation, just look at the displayBFS function below.
Level Bypass order of common tree (n-ary tree) in java
Thanks!
void displayBFS(NaryTreeNode n) { Queue<NaryTreeNode> q = new LinkedList<NaryTreeNode>(); System.out.println(n.data); while(n!=null) { for(NaryTreeNode x:n.nary_list) { q.add(x); System.out.print(x.data + " "); } n=q.poll(); System.out.println(); } } Current Tree Structure for reference: root(100) / | \ 90 50 70 / \ 20 30 200 300 Current Output: 100 90 50 70 20 30 200 300 Expected Output 100 90 50 70 20 30 200 300
In addition, I previously sent a logical problem with the same function, since this was answered, and the current question is real to another problem, I posted a new question, is this approach suitable or should I make changes to the previous question and not open a new one?
source share