• + 0 comments

    Without heavy light decomposition, I have been able to pass the three cases:

    The part of the code that sets up the tree:

    struct node{
        int parent=-1;
        int ltree=-1;
        int rtree=-1;
        int data;
        int max;
        queue<int> neighbours;
    };
    
    int build(vector<node>& tree, vector<vector<int>>& edges){
        int temp; // for swapping if need be
    
        // O(n) - setting up undirected acyclic graph
        for(int i=0; i<edges.size(); i++){
            tree[edges[i][0]].neighbours.push(edges[i][1]);
            tree[edges[i][1]].neighbours.push(edges[i][0]);
        }
    
        // O(n) - finding root
        int root = -1;
        for(int i=0; i<tree.size(); i++){
            if (tree[i].neighbours.size() == 2) {
                root=i;
                break;
            }
        }
    
        // setting up the tree
        queue<int> rem_nodes;
        rem_nodes.push(root);
        while(!rem_nodes.empty()){
            node& curr_node = tree[rem_nodes.front()];
            while(!curr_node.neighbours.empty()){
                if (curr_node.parent != curr_node.neighbours.front()){
                    if (curr_node.ltree = -1){
                        curr_node.ltree = curr_node.neighbours.front();
                        rem_nodes.push(curr_node.ltree);
                        tree[curr_node.ltree].parent = rem_nodes.front();
                    }else{
                        curr_node.rtree = curr_node.neighbours.front();
                        rem_nodes.push(curr_node.rtree);
                        tree[curr_node.rtree].parent = rem_nodes.front();
                    }
                }
                curr_node.neighbours.pop();
            }
            rem_nodes.pop();
        }
        return root;
    }
    

    It took a while to figure out that the parent may not have a smaller node-number than the child. For example: