题解 | #在二叉树中找到两个节点的最近公共祖先#
在二叉树中找到两个节点的最近公共祖先
http://www.nowcoder.com/practice/e0cc33a83afe4530bcec46eba3325116
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * } */ public class Solution { /** * * @param root TreeNode类 * @param o1 int整型 * @param o2 int整型 * @return int整型 */ public int lowestCommonAncestor (TreeNode root, int o1, int o2) { ArrayList<Integer> array1 = new ArrayList<>(); ArrayList<Integer> array2 = new ArrayList<>(); searchOnTree(root, array1, o1); searchOnTree(root, array2, o2); int result = 0; int index1 = array1.size() - 1; int index2 = array2.size() - 1; while (index1 >= 0 && index2 >= 0 && array1.get(index1) == array2.get(index2)) { result = array1.get(index1); index1--; index2--; } return result; } private boolean searchOnTree(TreeNode root, ArrayList<Integer> array, Integer target) { if (root == null) { return false; } boolean isSearch = root.val==target || searchOnTree(root.left, array, target) || searchOnTree(root.right, array, target); if (isSearch) { array.add(root.val); } return isSearch; } }