Sort by

recency

|

955 Discussions

|

  • + 0 comments

    DFs:

    public static void top(Node root,Map m,int w,int h){

        if(root == null) return;
    
        if(!m.containsKey(w))  
            m.put(w, new int[]{h,root.data});
        else if(m.get(w)[0] > h)
            m.put(w, new int[]{h,root.data});
    
        top(root.left, m,w-1,h+1);
        top(root.right, m, w+1,h+1);
    

    }

    public static void topView(Node root) {

        Map<Integer,int[]> m = new TreeMap<Integer,int[]>();
        top(root,m,0,0);
        for(int k : m.keySet()){
            System.out.print(m.get(k)[1] + " ");
        }
    }
    
  • + 0 comments
    /*
    class Node {
        public:
            int data;
            Node *left;
            Node *right;
            Node(int d) {
                data = d;
                left = NULL;
                right = NULL;
            }
    };
    
    */
    
       void topView(Node* root) {
        if (!root) return;
        queue<pair<Node*, int>> q;
        map<int, int> mp;
        q.push({ root, 0 });
        while (q.size()) {
            auto temp = q.front();
            q.pop();
            int horizontal_distance = temp.second;
            Node* node = temp.first;
            if (!mp[horizontal_distance]) {
                mp[horizontal_distance] = node->data;
            }
            if (node->left) {
                q.push({ node->left, horizontal_distance - 1 });
            }
            if (node->right) {
                q.push({ node->right, horizontal_distance + 1 });
            }
        }
        for (auto node : mp) {
            cout << node.second << ' ';
        }
    }
    
  • + 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

  • + 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=" ")