【问题标题】:Maximum distance between two nodes in a tree树中两个节点之间的最大距离
【发布时间】: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--;

            }
        }


    }

}

程序似乎正在运行;但未显示某些测试用例的正确输出。我采取的方法是:

  1. 求根节点的子节点数(我一直把根节点取为0)。
  2. 找出每个子树的最大深度(与根节点的子节点一样多的子树)。
  3. 将每个子树的最大深度存储在ArrayList 中,对其进行排序并打印最后两个值的总和。

有人可以指出我程序中的错误吗?

【问题讨论】:

    标签: java algorithm tree


    【解决方案1】:

    错误首先在算法中。 您假设两个节点之间的最大距离始终包含根节点,但这并不总是成立。

    这是一个例子:

    最长路径的节点用红色标记。 最长路径的长度为 6 并包含 7 节点,而您的算法仅找到通过根的路径,因此打印 5 作为其答案。

    【讨论】:

    • 谢谢。犯了这么幼稚的错误真是太傻了。
    • @PrashantPandey,如果您正在寻找,请接受答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 1970-01-01
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    相关资源
    最近更新 更多