Sort by

recency

|

960 Discussions

|

  • + 0 comments

    Here's My Python 3 Code

    Any suggestion to increase efficiency are appreciated please

    def topView(root):
        from collections import deque
        if not root:
            return
        top_nodes = {}
        queue = deque([(root, 0)])
        while queue:
            node, hd = queue.popleft()
            if hd not in top_nodes:
                top_nodes[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(top_nodes):
            print(top_nodes[hd], end=" ")
        print()
    
  • + 0 comments

    I am pretty sure this question has changed over time. 20/20 answers from top leader boards in java don't pass.

  • + 0 comments

    Problem's description must be way more clear; a math definition for "top view" may be better.

  • + 0 comments

    public static void topView(Node root) { if (root == null) { return;

    }
    

    Queue> queue = new LinkedList<>(); // Map to store the first node at each horizontal distance Map map = new TreeMap<>();

        // Start with the root node and horizontal distance 0
        queue.offer(new AbstractMap.SimpleEntry<>(root, 0));
    
        while (!queue.isEmpty()) {
            Map.Entry<Node, Integer> entry = queue.poll();
            Node node = entry.getKey();
            int horizontalDistance = entry.getValue();
    
            // If the horizontal distance is not yet in the map, add it
            if (!map.containsKey(horizontalDistance)) {
                map.put(horizontalDistance, node.data);
            }
    
            // If the node has a left child, enqueue it with horizontal distance - 1
            if (node.left != null) {
                queue.offer(new AbstractMap.SimpleEntry<>(node.left, horizontalDistance - 1));
            }
    
            // If the node has a right child, enqueue it with horizontal distance + 1
            if (node.right != null) {
                queue.offer(new AbstractMap.SimpleEntry<>(node.right, horizontalDistance + 1));
            }
        }
    
        // Print the top view by iterating over the map
        for (int value : map.values()) {
            System.out.print(value + " ");
        }
    }
    
  • + 0 comments

    from collections import deque def topView(root): if(root==None): return 0 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))
    print(" ".join(str(hd_map[hd]) for hd in sorted(hd_map)))