Home Find a node at the same level in a tree for a given node?

# Find a node at the same level in a tree for a given node?

wittyButterfly
1#
wittyButterfly Published in 2018-01-13 02:09:29Z
 I have to find the nodes in the same level when one of the level member is given as input. But I was unable to get the estimated output. I did not find where my code wrong. I am giving my code at which I was unable to recognize the mistake. Can some one explain the mistake I did in the code? My sample input and output is,  10 / \ 17 12 / \ / \ 10 8 1 3  Ex:- Input:17 output :12 Input:1 output:8 or 3 or 10 Here is my sample code, public void printNode(Node node) { Queue que = new LinkedList(); Queue aux = new LinkedList(); que.add(root); while(!que.isEmpty()) { Node temp = que.poll(); System.out.println(temp+" "); if(temp.left != null) { que.add(temp.left); aux.add(temp.left); } if(temp.right != null) { que.add(temp.right); aux.add(temp.right); } if(aux.contains(node)) { while(!aux.isEmpty()) { if(aux.poll() != node) System.out.print(aux.poll()+" "); } } else { aux.clear(); } } } 
Yi Tang
2#
Yi Tang Reply to 2018-01-13 02:30:32Z
 Nodes with same level after target node are not enque aux when you check aux.contains(node).
 You need to login account before you can post.
Processed in 0.42901 second(s) , Gzip On .