求两个节点的最近公共祖先节点

import java.util.Scanner; /** * 1330 Nearest Common Ancestors * Time Limit: 1000MS Memory Limit: 10000K * Total Submissions: 4632 Accepted: 2438 * @author zhtsuc * */ public class NearestCommonAnestor { private int[] arr; public void solve(){ Scanner in = new Scanner(System.in); int caseNum = in.nextInt(); while(caseNum != 0){ int nodeNum = in.nextInt(); arr = new int[nodeNum + 1]; for(int i = 1; i <= nodeNum - 1; i++){ int parentNode = in.nextInt(); int childNode = in.nextInt(); arr[childNode] = parentNode; } int firstNode = in.nextInt(); int secondNode = in.nextInt(); int nearestCommonAnestor = getNearestCommonAnestor(firstNode, secondNode); System.out.println(nearestCommonAnestor); caseNum--; } } private int getNearestCommonAnestor(int firstNode, int secondNode){ while(firstNode != 0){ if (isParent(secondNode, firstNode)){ return firstNode; } firstNode = arr[firstNode]; } return -1; } private boolean isParent(int srcNode, int parentNode){ int node = srcNode; while(node != 0){ if (node == parentNode){ return true; } node = arr[node]; } return false; } public static void main(String[] args) { NearestCommonAnestor tree = new NearestCommonAnestor(); tree.solve(); } }  

你可能感兴趣的:(求两个节点的最近公共祖先节点)