首页 > 其他 > 详细

LeetCode-235

时间:2021-08-08 11:24:54      阅读:16      评论:0      收藏:0      [点我收藏+]

235. Lowest Common Ancestor of a Binary Search Tree


原题链接


描述

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”


示例

技术分享图片

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2
Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

思路

对于祖先结点T,一定有 T.val >= p.val && T.val <= q.val。如果 p、q 的 val 都小于 root.val,那么p、q 的 LCA 一定在 root 的左子树上;如果 p、q 的 val 都大于 root.val,那么p、q 的 LCA 一定在 root 的右子树上;否则一旦出现其他情况,那么该结点就是 p、q 的 LCA。


解答

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) return null;
        if (root.val >p.val && root.val>q.val) return lowestCommonAncestor(root.left,p,q);
        if (root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right,p,q);

        return root;
    }
}

LeetCode-235

原文:https://www.cnblogs.com/klaus08/p/15113902.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!