LeetCode-Algorithms-[Easy]235. 二叉搜索树的最近公共祖先

    技术2025-09-22  6

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

    百度百科中最近公共祖先的定义为:“对于有根树 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 为不同节点且均存在于给定的二叉搜索树中。

    来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


    直接利用BST的性质来解

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null) { return null; } int pValue = p.val; int qValue = q.val; int nodeValue = root.val; if (nodeValue > pValue && nodeValue > qValue) { return lowestCommonAncestor(root.left, p, q); } if (nodeValue < pValue && nodeValue < qValue) { return lowestCommonAncestor(root.right, p, q); } return root; }

    其实如果不知道这个性质也没关系,可以逐步分析,用直接法来解这个题

    public TreeNode lowestCommonAncestor_2(TreeNode root, TreeNode p, TreeNode q) { if (root == null) { return null; } int q_val = q.val, p_val = p.val; if (p_val > q_val) { return lowestCommonAncestor(root, q, p); } if (root == p) { TreeNode right = lowestCommonAncestor(root.right, p, q); if (right == q) { return root; } return root; } if (root == q) { TreeNode left = lowestCommonAncestor(root.left, p, q); if (left == p) { return root; } return root; } int node_val = root.val; if (node_val < p_val) { return lowestCommonAncestor(root.right, p, q); } if (node_val > q_val) { return lowestCommonAncestor(root.left, p, q); } TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if (left == p && right == q) { return root; } if (left != null) { return left; } if (right != null) { return right; } return null; }
    Processed: 0.011, SQL: 9