We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
By top view does it mean by top view? From provided example it looks like it traversed only right child only, and the there was no left child in the sample input and output provided. So in case of presence of left child to root will it also traverse left childrens too. In any case I wrote the following java code for traversing left chilrens and right childrens from root and seems to work for base testcase:
publicstaticvoidtopView(Noderoot){List<Integer>ar=newArrayList<Integer>();//start at rootNodecur=root;ar.add(cur.data);//traverse all left childrenwhile(cur.left!=null){cur=cur.left;ar.add(cur.data);}cur=root;//traverse all right childrenwhile(cur.right!=null){cur=cur.right;ar.add(cur.data);}for(inti:ar){System.out.print(i+" ");}}
Please suggest improvements to this code. Thanks
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Tree : Top View
You are viewing a single comment's thread. Return to all comments →
By top view does it mean by top view? From provided example it looks like it traversed only right child only, and the there was no left child in the sample input and output provided. So in case of presence of left child to root will it also traverse left childrens too. In any case I wrote the following java code for traversing left chilrens and right childrens from root and seems to work for base testcase:
Please suggest improvements to this code. Thanks