We need to calculate sumv(sum of all the numbers in the subtree of vertex v) and m1v and m2v (the maximum and second maximum from all sum in the subtree of vertex v except v). Update answer after calculating m1v and m2v for each vertex. This can be done using one DFS, refer to my code for the detailed implementation.