递归写法:
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) {
// write code here
return help(root, o1, o2).val;
}
private TreeNode help(TreeNode root, int x, int y){
if (root == null || root.val == x || root.val == y){
return root;
}
TreeNode left = help(root.left, x, y);
TreeNode right = help(root.right, x, y);
if (left == null){
return right;
}
if (right == null){
return left;
}
return root;
}
}
迭代写法:
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 m, int n) {
// write code here
Map<Integer ,Integer> map = new HashMap<>();
Queue<TreeNode> deque = new LinkedList<>();
map.put(root.val, Integer.MAX_VALUE);
deque.add(root);
while (!map.containsKey(m) || !map.containsKey(n)){
TreeNode temp = deque.poll();
if (temp.left != null){
deque.add(temp.left);
map.put(temp.left.val, temp.val);
}
if (temp.right != null){
deque.add(temp.right);
map.put(temp.right.val, temp.val);
}
}
Set<Integer> set = new HashSet<>();
// 找到节点1的所有父节点
while (map.containsKey(m)){
set.add(m);
m = map.get(m);
}
while(!set.contains(n)){
n = map.get(n);
}
return n;
}
}