Sort by

recency

|

952 Discussions

|

  • + 0 comments

    This question is so terribly defined it makes me wanna p*** in the cereal of whoever made this question. What defines a view of a tree as being top down? Well in the problem description its defined in one single example EXCEPT THE F****** EXAMPLE DOESN'T COVER 80% OF HOW THE VIEW IS DEFINED.

    Assuming all branches are evenly spaced: i.e. a left branch is 1 unit down and 1 unit to the left of its parent, the highest branch to be left or right of the root and all of its proceeding children will be what you could see. For example, if the root node has a left child, the left child and all of its left children are what you can see. The highest/first child to be right of the root and all of its right sided children would be visible as well.

    If you had: 1 \ 15 / 3 / \ 2 4 Then you could see 15 and all of its proceeding right children, you could also see two since its left of 1 and all of its left children. Since all diagnal lines you could form all have a slope of 1 or -1, you could never have a situation where you could see one of four's imaginarily infine right sided children because 15 set the line of sight at a higher point. Same logic follows that four's imaginarily infine left sided children could never enter the line of sight of root because 2 already determined roots left sided line of sight.

    I made one other assumption that branches / connections between branches were opaque. I wrote code based on these priciples. F*** this problem.

    `def topView(root, direction="Root"):

    leftNode = None
    rightNode = None
    
    values = []
    queue = Queue()
    queue.enqueue((root, 0))
    
    while queue.isEmpty() is False and (leftNode is None or rightNode is None):
        node = queue.dequeue()
        #print(f"node observered: {node[0].info}, it's x: {node[1]}")
    
        if node[1] > 0 and rightNode is None:
            rightNode = node[0]
            #print(f"right node assgned: {rightNode.info}")
    
        if node[1] < 0 and leftNode is None:
            leftNode = node[0]
            #print(f"left node assgned: {leftNode.info}")
    
        if node[0].left is not None:
            #print(f"left: {node[0].left.info}")
            queue.enqueue((node[0].left, node[1] - 1))
    
        if node[0].right is not None:
            #print(f"right: {node[0].right.info}")
            queue.enqueue((node[0].right, node[1] + 1))
    
    while leftNode is not None:
        print(f" lefts value: {leftNode.info}")
        values.append(str(leftNode.info))
        leftNode = leftNode.left
    
    values = list(reversed(values))
    values.append(str(root.info))
    
    while rightNode is not None:
        print(f" rights value: {rightNode.info}")
    
  • + 0 comments

    """ Node is defined as self.left (the left child of the node) self.right (the right child of the node) self.info (the value of the node) """ def tree_Coords(root, d, radius, level): if not root: return if level not in d.keys(): d[level] = dict() d[level].update({radius: root.info}) tree_Coords(root.left, d, radius-1, level+1) tree_Coords(root.right, d, radius+1, level+1)

    def topView(root): radius = 0 level = 0 if not root: return d = dict() tree_Coords(root, d, radius, level) res = dict()

    # Nested loop scans and adds values to res when no value exists for
    # a specific radius. If raidus index already exists in res, then there existed
    # another value with the same radius on a previous level(above).
    for level in d.keys():
        for radius in d[level].keys():
            if radius not in res.keys():
                res[radius] = d[level][radius]
    
    for r in sorted(res.keys()):
        print(res[r], end=" ")
    
  • + 0 comments
    def topView(root):
        if not root:
            return
        
        hd_map = {}
        
        queue = deque([(root, 0)])
        
        while queue:
            node, hd = queue.popleft()
            if hd not in hd_map:
                hd_map[hd] = node.info
                
            if node.left:
                queue.append((node.left, hd - 1))
            if node.right:
                queue.append((node.right, hd + 1))
        for hd in sorted(hd_map.keys()):
            print(hd_map[hd], end=" ")
    
  • + 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.

  • + 0 comments

    Hello everyone!

    I've struggles with solving this problem.

    1) I can't understand the input provided, I assume it's a node with data, left and right properties.

    2) And this is my javascript solution which prints nothing:

    function processData(input) {
    
        function printTopView(root) {
            const result = [];
    
            if (root.left) goLeft(root.left);
    
            result.push(root.data);
    
            if (root.right) goRight(root.right);
    
            console.log(result.join(' '));
    
            function goLeft(node) {
                if (node.left) goLeft(node.left); 
                result.push(node.data);
            }
    
            function goRight(node) {
                result.push(node.data);
                if (node.right) goRight(node.right); 
            }
        }
    
        printTopView(input);
    }