一.非递归法
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 o1 int整型
* @param o2 int整型
* @return int整型
*/
public int lowestCommonAncestor (TreeNode root, int o1, int o2) {
// write code here
//如果是空树,返回结点值
if (root == null) {
return root.val;
}
//如果只有一个根结点且o1和o2都指向根结点,那么最近祖先就是结点值
if ((root.left == null && root.right == null) &&
o1 == root.val && o2 == root.val) {
return root.val;
}
//记录遍历到子节点时的父节点
Map<Integer, Integer> map = new HashMap<>();
//队列用来遍历每一层
Queue<TreeNode> queue = new LinkedList<>();
//给父节点一个默认值
map.put(root.val,Integer.MIN_VALUE);
//把根结点入队
queue.offer(root);
//当key值没有o1和o2时,进入while循环
while (!map.containsKey(o1) || !map.containsKey(o2)) {
TreeNode node = queue.poll();
//记录根结点的下一层,把根结点的值保存一下
if (node.left != null) {
map.put(node.left.val, node.val);
queue.offer(node.left);
}
if (node.right != null) {
map.put(node.right.val, node.val);
queue.offer(node.right);
}
}
Set<Integer> set = new HashSet<>();
//记录下o1和他的祖先节点,从o1节点开始一直到根节点
while (map.containsKey(o1)) {
set.add(o1);
o1 = map.get(o1);
}
//查看o1和他的祖先节点是否包含o2节点,如果不包含再看是否包含o2的父节点
while (!set.contains(o2)) {
o2 = map.get(o2);
}
return o2;
}
}
二.递归法
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 o1 int整型
* @param o2 int整型
* @return int整型
*/
public int lowestCommonAncestor (TreeNode root, int o1, int o2) {
// write code here
//如果是空树,返回结点值
if (root == null) {
return root.val;
}
//如果只有一个根结点且o1和o2都指向根结点,那么最近祖先就是结点值
if ((root.left == null && root.right == null) &&
o1 == root.val && o2 == root.val) {
return root.val;
}
return binaryTree(root,o1,o2).val;
}
private TreeNode binaryTree(TreeNode root,int o1,int o2) {
//找到一个相等的值,返回root
if (root == null || o1 == root.val || o2 == root.val) {
return root;
}
//递归左右子树
TreeNode left = binaryTree(root.left,o1,o2);
TreeNode right = binaryTree(root.right,o1,o2);
//在左子树上找见了,或者全在右子树
if (left == null) {
return right;
}
//在左=右子树上找见了,或者全在左子树
if (right == null) {
return left;
}
return root;
}
}