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

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

user1381
1#
user1381 Published in June 24, 2018, 3:09 am

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<Node> que = new LinkedList<Node>();
    Queue<Node> aux = new LinkedList<Node>();
    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();
        }
    }
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.315981 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO