题解 | #二叉搜索树的最近公共祖先#
二叉搜索树的最近公共祖先
https://www.nowcoder.com/practice/d9820119321945f588ed6a26f0a6991f
方法一:搜索路径比较
1. 搜索二叉树每个结点的值唯一,且每一个结点都满足 left < root < right
- 根据搜索二叉树的性质可直接通过比较结点值的大小找到结点位置
2. 一个节点也可以是它自己的祖先,所以必须把待搜索的结点本身也加入搜索路径中
ArrayList<Integer> pPath = new ArrayList<>(); ArrayList<Integer> qPath = new ArrayList<>(); public int lowestCommonAncestor (TreeNode root, int p, int q) { // write code here findPath(root,p,pPath); findPath(root,q,qPath); int res = 0; for(int i=0;i<pPath.size()&&i<qPath.size();i++){ int x = pPath.get(i); int y = qPath.get(i); if(x==y){ res = pPath.get(i);//每次相等更新公共父结点直到最深的一个 }else{ break; } } return res; } public void findPath(TreeNode root,int value,ArrayList arr){ TreeNode cur = root; while(value!=cur.val){ arr.add(cur.val); if(value>cur.val){ cur = cur.right; }else{ cur = cur.left; } } arr.add(cur.val);//循环结束再加最后一次 //必须加入待查找的结点本身,否则重合路径不包括他 }
方法二:递归,一次遍历
二叉搜索树里,只有两个结点的最近公共祖先会把这两个结点放在两侧,上面的祖先都是把它们放在一侧!
public int lowestCommonAncestor (TreeNode root, int p, int q) { // write code here TreeNode cur=root; //必须是带等号的,别忘了结点本身也可以是公共父结点! if((p>=cur.val&&q<=cur.val)||(q>=cur.val&&p<=cur.val))return cur.val; if((p>=cur.val&&q>=cur.val)){ return lowestCommonAncestor(cur.right,p,q); } return lowestCommonAncestor(cur.left,p,q); }