• + 1 comment

    Title: Why is my top view function returning incorrect results for a binary search tree?

    Hi everyone,

    I’m trying to implement the top view of a binary search tree in Java, but my output isn’t matching my expectations. After debugging my code, I suspect I may not fully understand the concept of the top view, and I’m getting an incorrect result.

    Problem:

    I’ve inserted nodes into a binary search tree in the following order:

    116 37 23 108 59 86 64 94 14 105 17 111 65 55 31 79 97 78 25 50 22 66 46 104 98 81 90 68 40 103 77 74 18 69 82 41 4 48 83 67 6 2 95 54 100 99 84 34 88 27 72 32 62 9 56 109 115 33 15 91 29 85 114 112 20 26 30 93 96 87 42 38 60 7 73 35 12 10 57 80 13 52 44 16 70 8 39 107 106 63 24 92 45 75 116 5 61 49 101 71 11 53 43 102 110 1 58 36 28 76 47 113 21 89 51 19 3
    

    My Approach:

    I’m using the following code to calculate the top view:

    public static void helper(Node root) {
        if (root != null) {
            helper(root.left);
            System.out.print(root.data + " ");
        }
    }
    
    public static void topView(Node root) {
        Node next = root.left;
        helper(next);
        
        System.out.print(root.data + " ");
        
        while(root.right != null) {
            root = root.right;
            System.out.print(root.data + " ");
        }    
    }
    

    Issue:

    When I run the program with the above input, I get the following output:

    1 2 4 14 23 37 108 111 115 116
    

    However, the expected output should be:

    1 2 4 14 23 37 108 111 115 116 83 84 85
    
    • What am I misunderstanding about the top view?
    • How should I adjust my code to correctly print the top view of the binary search tree?

    Thank you in advance for your help!


    This version should make your issue and expectations clear to others, inviting them to help you debug the code further.