• + 0 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:

    public static void topView(Node root) {
          List<Integer> ar = new ArrayList<Integer>();
          //start at root
          Node cur = root;
          ar.add(cur.data);
          //traverse all left children
          while(cur.left!=null){
              cur = cur.left;
              ar.add(cur.data);
          }
          
          cur = root;
          //traverse all right children
          while(cur.right!=null){
              cur = cur.right;
              ar.add(cur.data);
          }
          
          for(int i:ar){
              System.out.print(i+" ");
          }
          
        }
    

    Please suggest improvements to this code. Thanks