1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { List<TreeNode> a = new ArrayList<>(), b = new ArrayList<>(); dfs(root, p, a); dfs(root, q, b); TreeNode ans = null; for (int i = 0; i < Math.min(a.size(), b.size()) && a.get(i) == b.get(i); ++i) { ans = a.get(i); } return ans; }
private boolean dfs(TreeNode cur, TreeNode target, List<TreeNode> path) { if (cur == null) return false; path.add(cur); if (cur == target || dfs(cur.left, target, path) || dfs(cur.right, target, path)) { return true; } else { path.remove(path.size() - 1); return false; } } }
|