Problem:
Diameter of a Tree

Given a tree T with non-negative weight, find the diameter of the tree.

The diameter of a tree is the maximum distance between two nodes in a tree.

Input

n
s1 t1 w1
s2 t2 w2
:
sn-1 tn-1 wn-1

The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively.

In the following n-1 lines, edges of the tree are given.

si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge.

Output

Print the diameter of the tree in a line.

Constraints

1 ≤ n ≤ 100,000

0 ≤ wi ≤ 1,000

Sample Input 1

4
0 1 2
1 2 1
1 3 3

Sample Output 1

5

Sample Input 2

4
0 1 1
1 2 2
2 3 4

Sample Output 2

7

Solution in JAVA (judge verdict: Wrong Answer)


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author prashant
 *
 */
public class Main {

	public static void main(String[] args) throws IOException{
		try(Scanner scanner = new Scanner(System.in)){
			int n = scanner.nextInt();
			Node[] nodes = new Node[n];
			for(int i = 0; i<n; i++){
				nodes[i] = new Node();				
			}
			for(int i=1;i<n;i++){
				nodes[scanner.nextInt()].addNode(nodes[scanner.nextInt()], scanner.nextInt());
			}
			System.out.println(nodes[0].getDiameter());
		}
	}
	
	
	static class Node {
		
		private List<Node> nodes = new ArrayList<>();
		private List<Integer> weigths = new ArrayList<>();
		
		private int weightedHeight = - 1;
		
		public void addNode(Node node, int weight){
			nodes.add(node);
			weigths.add(weight);
		}
		
		public int getWeightedHeight(){
			if(weightedHeight != -1) return weightedHeight;
			int wheight = 0;
			for (int i=0;i<nodes.size();i++){
				wheight = Math.max(wheight,weigths.get(i) + nodes.get(i).getWeightedHeight());
			}
			weightedHeight = wheight;
			return wheight;
		}
		
		public int getDiameter(){
			int diameter = 0;
			int h1 = 0, h2 = 0;
			Integer i1 = null, i2 = null;
			for (int i=0;i<nodes.size();i++){
				diameter = Math.max(diameter, nodes.get(i).getDiameter());
				int height = nodes.get(i).getWeightedHeight();
				if(height > h2 && height < h1){
					h2 = height;
					i2 = i;
				}
				if(height >= h1){
					h2 = h1;
					h1 = height;
					i2 = i1;
					i1 = i;
				}
			}
			if(i1 != null && i2 != null){
				diameter = Math.max(diameter, h1 + h2 + weigths.get(i1) + weigths.get(i2));				
			}
			else if (i1 != null){
				diameter = Math.max(diameter, h1 + weigths.get(i1));					
			}else if (i2 != null){
				diameter = Math.max(diameter, h2 + weigths.get(i2));				
			}
			return diameter;
		}
	}
}