package JianZhioffer; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; /** * 二叉搜索树的最近公共祖先 * 给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。 */ public class test68I { public static void main(String[] args) { TreeNode t=new TreeNode(6); t.left=new TreeNode(2); t.right=new TreeNode(8); t.left.left=new TreeNode(0); t.left.right=new TreeNode(4); t.right.left=new TreeNode(7); t.right.right=new TreeNode(9); t.left.right.left=new TreeNode(3); t.left.right.right=new TreeNode(5); TreeNode p=t.left; TreeNode q=t.left.right; TreeNode result=lowestCommonAncestor(t,p,q); int x=0; } //思路:递归/迭代,p和q和最近公共祖先的关系: //1.都在左子树 p.val<root.val ,q.val<root.val, 那么去root.left继续判断 //2.都在右子树 p.val>root.val ,q.val>root.val, 那么去root.right继续判断 //3.一左一右 直接返回 public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { while(root!=null){ if(p.val<root.val&&q.val<root.val){ root=root.left; }else if(p.val>root.val&&q.val>root.val){ root=root.right; }else{ break; } } return root; } //超出内存限制了。。 public static TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) { if(root==null){ return null; } Queue<TreeNode> que=new LinkedList<>(); List<TreeNode> ts=new ArrayList<>(); que.offer(root); while(!que.isEmpty()){ int x=que.size(); TreeNode t=que.poll(); for(int i=0;i<x;i++){ if(t.left!=null){ que.offer(t.left); } if(t.right!=null){ que.offer(t.right); } ts.add(t); } } Map<TreeNode,List<Integer>> map=new LinkedHashMap<>(); for(int i=0;i<ts.size();i++){ TreeNode temp=ts.get(i); List<Integer> list=new ArrayList(); helper(temp, list); map.put(temp, new ArrayList<>(list)); } TreeNode x=null; for(TreeNode t:map.keySet()){ List<Integer> list=map.get(t); if(list.contains(p.val)&&list.contains(q.val)){ x=t; } } return x; } public static void helper(TreeNode root, List<Integer> list) { while(root!=null&&!list.contains(root.val)){ list.add(root.val); helper(root.left, list); helper(root.right, list); } } }