【LeetCode】二叉搜索树的最近公共祖先Java题解

103 阅读2分钟

这是我参与8月更文挑战的第24天,活动详情查看:8月更文挑战

题目描述

给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”


示例 1:

输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
输出: 6 
解释: 节点 2 和节点 8 的最近公共祖先是 6。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-zui-jin-gong-gong-zu-xian-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路分析

  • 今天的算法每日一题,是求树的公共祖先。题目介绍了公共祖先的定义。
  • 若 root 是 p,q 的 最近公共祖先 ,则只可能为以下情况之一:
  • p 和 q 在 root 的子树中,且分列 root 的 异侧(即分别在左、右子树中);
  • p = root ,且 q 在 root 的左或右子树中;
  • q = root ,且 p 在 root 的左或右子树中;
  • 今天的这个题目还有一个条件是,这个树是二叉搜索树。二叉搜索树的中序遍历是升序。通过这个特性,我们可以快速判断p, q节点和 root 的位置关系。代码如下:

通过代码

/**
 * 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.left;
            } else if (p.val > ancestor.val && q.val > ancestor.val) {
                ancestor = ancestor.right;
            } else {
                break;
            }
        }

        return ancestor;
    }
}

image.png

总结

  • 上述算法的时间复杂度是O(n), 空间复杂度是O(1)
  • 坚持算法每日一题,加油!