想到了要用后序遍历或者层次遍历,判定条件却没想出,看了大佬的思路才知道的。
1.后序遍历
一共三种情况:两个结点在根结点的右子树(根结点的左子树为空);两个结点在根结点的左子树(根结点的右子树为空);一个结点在根结点的左子树,一个结点在根结点的右子树;时间复杂度:O(n),遍历每个结点;空间复杂度:O(n),递归的深度;
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
if(root==null)
return 0;
return postOrder(root,o1,o2).val;
}
public TreeNode postOrder(TreeNode root, int o1, int o2){
if(root==null||root.val==o1||root.val==o2)//找到值,返回根结点
return root;
TreeNode left=postOrder(root.left,o1,o2);
TreeNode right=postOrder(root.right,o1,o2);
if(left==null)//左子树为空,说明两个结点在root的右子树上
return right;
if(right==null){//右子树为空,说明两个结点在root的左子树上
return left;
}
return root;//一个结点在root的左子树,一个在右子树
}
}
2.层次遍历(BFS)
从根结点到叶子结点进行层次遍历,用一个哈希表保存父结点,即子结点到根结点的路径,一个队列用于层次遍历,然后进行一次层次遍历存上父结点。然后用一个集合保存o1到根结点的路径,最后再找到o1到根结点的路径中包含o2的父结点的最短的路径。时间复杂度:O(n),遍历每一个结点;空间复杂度:O(n),辅助空间一个哈希表,一个队列,一个集合。
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
if(root==null)
return 0;
Queue<treenode> q=new LinkedList<>();
q.offer(root);
Map<Integer,Integer> parent=new HashMap<>();//用于存放父结点
parent.put(root.val,Integer.MIN_VALUE);//根节点没有父结点,给其一个默认值
while(!q.isEmpty()){//层次遍历
TreeNode t=q.poll();
if(t.left!=null){//左结点不为空,记录父结点
parent.put(t.left.val,t.val);
q.offer(t.left);
}
if(t.right!=null){//右结点不为空,记录父结点
parent.put(t.right.val,t.val);
q.offer(t.right);
}
}
Set<integer> ancestors=new HashSet<>();
//记录o1以及它的父结点,即从o1到根结点的路径
while(parent.containsKey(o1)){
ancestors.add(o1);
o1=parent.get(o1);
}
//找到从o1到根路径中包含o2的父结点最短路径,即得最近公共祖先o2
while(!ancestors.contains(o2))
o2=parent.get(o2);
return o2;
}
}</integer></treenode>