20二叉搜索树的最近公共祖先
本题的两个关键:
- 如何利用BST的性质来搜索
- 为何一个节点在pq中间,那么这个节点就一定是最近公共祖先
class Solution {
//向下遍历,如果遍历到一个节点在pq中间,那么这个节点就一定是最近公共祖先
TreeNode res = null;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
TreeNode small = p.val > q.val ? q : p;
TreeNode big = null;
if(small != p) big = p;
else big = q;
res = traversal(root, small, big);
return res;
}
TreeNode traversal(TreeNode root, TreeNode small, TreeNode big) {
if(root == null) return root;
// if(root == small || root == big) {}
TreeNode left = null;
TreeNode right = null;
if(root.val > small.val && root.val > big.val){
//最近公共祖先在左子树
left = traversal(root.left, small, big);//返回值是本树的最近公共祖先
}
else if(root.val >= small.val && root.val <= big.val) {
return root;
}
else if(root.val < small.val && root.val < big.val) {
right = traversal(root.right, small, big);
}
if(left != null) return left;
if(right != null) return right;
return null;
}
}
class Solution {
//向下遍历,如果遍历到一个节点在pq中间,那么这个节点就一定是最近公共祖先
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null) return root;
if(root.val > p.val && root.val > q.val){
//最近公共祖先在左子树
TreeNode left = lowestCommonAncestor(root.left, p, q);//返回值是本树的最近公共祖先
if(left != null) return left;
}
if(root.val < p.val && root.val < q.val) {
//公共祖先在右子树
TreeNode right = lowestCommonAncestor(root.right, p, q);
if(right != null) return right;
}
return root;
}
}
class Solution {//迭代法
//向下遍历,如果遍历到一个节点在pq中间,那么这个节点就一定是最近公共祖先
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null) return root;
TreeNode cur = root;
while(cur != null) {
if(cur.val < p.val && cur.val < q.val) {
cur = cur.right;
}
else if(cur.val > p.val && cur.val > q.val) {
cur = cur.left;
}
else return cur;
}
return null;
}
}
本题与19的遍历区别就是本题不必要遍历到pq,也就是说没必要见到pq,所以就没了遇见pq就返回这句话,本题思路也就是单纯遇到一个节点判断与pq大小关系从而来获取答案,而上面一题需要进行回溯也就是遍历过了pq才能得到答案。本题终止条件也就只有遇到空节点的返回,当然加上原先那句话不会出现错误