【发布时间】:2016-04-18 17:38:19
【问题描述】:
我试图找到树中两个节点之间的最大距离。这是我的程序:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class distance {
static ArrayList<ArrayList<Integer>> list=new ArrayList<ArrayList<Integer>>();
static ArrayList<Integer> visited=new ArrayList<Integer>();
static ArrayList<Integer> depth=new ArrayList<Integer>();
static ArrayList<Integer> depth1=new ArrayList<Integer>();
static int sum=-1;
static boolean[] arr;
static int root=0;
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
int n=in.nextInt(); //no of nodes
for(int i=0;i<=n;i++)
{
list.add(new ArrayList<Integer>());
}
int a;
int b;
for(int i=0;i<n-1;i++) //populating the adjacency list
{
a=in.nextInt();
b=in.nextInt();
list.get(a).add(b);
list.get(b).add(a);
}
arr=new boolean[n+1];
dfs(root);
int final_sum=0;
Collections.sort(depth1);
System.out.println(depth1.get(depth1.size()-1)+depth1.get(depth1.size()-2));
}
public static void dfs(int n)
{
arr[n]=true;
visited.add(n);
sum=sum+1;
if(list.get(n).size()==1)
{
depth.add(sum); //add the depth to the arraylist when we reach a leaf node.Note the this will not run if the root node has only one child but I've ignored the case.
}
if(n==root)
{
for(int j=0;j<list.get(0).size();j++)
{
dfs(list.get(0).get(j)); //recursion on each child of the root node
sum=0;
Collections.sort(depth);
depth1.add(depth.get(depth.size()-1));
depth.clear();
}
}
else
{
for(int l:list.get(n))
if(!arr[l]==true)
{
dfs(l);
sum--;
}
}
}
}
程序似乎正在运行;但未显示某些测试用例的正确输出。我采取的方法是:
- 求根节点的子节点数(我一直把根节点取为0)。
- 找出每个子树的最大深度(与根节点的子节点一样多的子树)。
- 将每个子树的最大深度存储在
ArrayList中,对其进行排序并打印最后两个值的总和。
有人可以指出我程序中的错误吗?
【问题讨论】: