PT07Z - Longest path in a tree

题目信息:

You are given an unweighted, undirected tree. Write a program to output the length of the longest path (from one node to another) in that tree. The length of a path in this case is number of edges we traverse from source to destination.

Input

The first line of the input file contains one integer N — number of nodes in the tree (0 < N <= 10000). Next N-1 lines contain N-1 edges of that tree — Each line contains a pair (u, v) means there is an edge between node u and node v (1 <= u, v <= N).

Output

Print the length of the longest path on one line.

Example

Input: 

1 2 
2 3

Output: 
2

 

分析:

题目大意就是给你一棵无权值,无向的树,求它的最长路径。

大概思路就是用LinkedList数组储存树,然后由无向树的性质可从任意一个点进行一次DFS,在DFS的过程中记录从该节点出发的路径的最长值并返回,由于最长路径可能不会经过出发结点,于是在对每一个点进行DFS时记录子路径的最长值和次长值并与当前最长路径比较,即可得出结果。

代码如下:

public class DFSSearch {

  private static Integer ans = 0;

  private static final LinkedList<Integer>[] lists = new LinkedList[1000];

  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("请输入节点数量:");
    int n = scanner.nextInt();
    scanner.nextLine();
    System.out.println("请输入节点坐标:");
    for (int i = 0; i < n - 1; i++){
      String[] tmp = scanner.nextLine().trim().split(" ");
      int u = Integer.parseInt(tmp[0]);
      int v = Integer.parseInt(tmp[1]);
      if (null == lists[u]){
        lists[u] = new LinkedList<>();
        lists[u].add(v);
      } else {
        lists[u].add(v);
      }
      if (null == lists[v]){
        lists[v] = new LinkedList<>();
        lists[v].add(u);
      } else {
        lists[v].add(u);
      }

    }

    scanner.close();

    DFS(1, n+1);
    //最多经过节点数减1即为最长路径的长度。
    System.out.println(ans - 1);
  }

  private static Integer DFS(int node, int previousNode){
      int len = lists[node].size();
      int Max = 0;
      int SMax = 0;
      for (int i = 0; i < len; i++){
        //不允许往回计算
        if (null != lists[node] && lists[node].get(i) == previousNode){
          continue;
        }
        int tmp = DFS(lists[node].get(i), node);
        if (tmp > Max){
          SMax = Max;
          Max = tmp;
        } else if (tmp > SMax){
          SMax = tmp;
        }
      }
      if (Max + SMax + 1 > ans){
        ans = Max + SMax + 1;
      }
      return Max + 1;

  }

}

另外,也可以通过树来做:

public class Solution {
    private int max = 0;

    /**
     * 通过自定义二叉树,找出一条所有节点均为相同值的最长路径。
     * 思路:通过查找是否相同根节点,定义一个全局变量
     * 注:递归返回最长的一边(单边最大值)
     * @param root
     * @return
     */
    public int getLongestPath(TreeNode root){
        if (null == root) return 0;
        backTree(root);
        return max;
    }
    private int backTree(TreeNode root){
        int left = root.left == null ? 0 :backTree(root.left);
        int right = root.right == null ? 0 : backTree(root.right);
        //递归判断是否根节点等于左右
        int resLeft = (root.left != null && root.value == root.left.value) ? left++ : 0;
        int resRight = (root.right != null && root.value == root.right.value) ? right++ : 0;

        max = Math.max(max, resLeft + resRight);
        //返回最长边
        return Math.max(resLeft, resRight);
    }

    class TreeNode{
        int value;
        TreeNode left;
        TreeNode right;
        TreeNode(int val){
            value = val;
        }

    }
}

题目来源:https://www.spoj.com/problems/PT07Z/

                  https://blog.csdn.net/qq_17550379/article/details/87380945

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值