剑指Offer68-1. 二叉搜索树的最近公共祖先Java版
1. 问题描述
给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5]
示例 1:
输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
输出: 6
解释: 节点 2 和节点 8 的最近公共祖先是 6。
示例 2:
输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
输出: 2
解释: 节点 2 和节点 4 的最近公共祖先是 2, 因为根据定义最近公共祖先节点可以为节点本身。
说明:
所有节点的值都是唯一的。
p、q 为不同节点且均存在于给定的二叉搜索树中。
2. 思路
2.1. 思路1
- 编写函数,查找从root到指定节点p的路径
- 调用函数,找到节点p和节点q与root之间的路径
- 找到路径中相同的节点,就是祖先。
2.2. 思路2
- 把root作为两个节点的公共祖先
- 如果p和q都大于ancestor,ancestor = ancesstor.right
- 如果p和q都小于ancestor,ancestor = ancesstor.left
2.3. 思路3
递归
3. 代码
3.1. 思路1代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
List<TreeNode> pathP, pathQ;
pathP = getPath(root, p);
pathQ = getPath(root, q);
TreeNode ancestor = null;
for (int i = 0; i < pathP.size()&& i <pathQ.size(); ++i) {
// 会找到最近的,如果是距离较远的那一个,会被较近的节点覆盖
if (pathP.get(i) == pathQ.get(i)) {
ancestor = pathP.get(i);
} else {
break;
}
}
return ancestor;
}
private List<TreeNode> getPath(TreeNode root, TreeNode target) {
List<TreeNode> path = new ArrayList<TreeNode>();
TreeNode p = root;
for(;p != target;) {
path.add(p);
if (target.val > p.val) {
p = p.right;
} else {
p = p.left;
}
}
path.add(p);
return path;
}
}
3.2. 思路2代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
TreeNode ancestor = root;
while(true) {
if (p.val > ancestor.val && q.val > ancestor.val) {
ancestor = ancestor.right;
} else if (p.val < ancestor.val && q.val < ancestor.val) {
ancestor = ancestor.left;
} else {
break;
}
}
return ancestor;
}
}
3.3. 思路3代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return null;
}
if (p.val > root.val && q.val > root.val) {
return lowestCommonAncestor(root.right, p, q);
}
if (p.val < root.val && q.val < root.val) {
return lowestCommonAncestor(root.left, p, q);
}
return root;
}
}