import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @param p int整型 * @param q int整型 * @return int整型 */ public static LinkedList<LinkedList<Integer>> linkedLists = new LinkedList<>(); public int lowestCommonAncestor (TreeNode root, int p, int q) { // write code here search(root, p, new LinkedList<>()); search(root, q, new LinkedList<>()); LinkedList<Integer> linkedList1 = linkedLists.get(0); LinkedList<Integer> linkedList2 = linkedLists.get(1); System.out.println(linkedList1); System.out.println(linkedList2); int length = Math.min(linkedList1.size(), linkedList2.size()); int index = 0; for (index=0; index < length; index++) { if (!linkedList1.get(index).equals(linkedList2.get(index))){ break; } } return linkedList1.get(index-1); } public static void search(TreeNode root, int p, LinkedList<Integer> linkedList) { if (root == null) { return; } linkedList.add(root.val); if (root.val == p) { linkedLists.add(new LinkedList<>(linkedList)); return; } search(root.left, p, linkedList); search(root.right, p, linkedList); linkedList.remove(linkedList.size() - 1); } }
本题考察的知识点是二叉树的遍历,所用编程语言是java。
我看了很多题解但是感觉挺复杂的,自己感觉并不需要那么复杂,我直接将从根节点到目标节点的两条路径都存储起来,然后将两条路径进行比较,第一个不相等的结点就是他们的最近公共祖先。