LeetCode 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树

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 v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
__6_
/ \
_2 _8
/ \ / \
0 _4 7 9
/ \
3 5

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

题意

给定一棵二分搜索树和两个节点,寻找这两个节点的最近公共祖先。

注意

二叉搜索树的性质:
每个节点的键值大于左孩子;每个节点的键值小于右孩子;以左右孩子为根的子树仍为二分搜索树

二叉树的操作:
插入 insert,查找 find, 删除 delete
最大值,最小值 minimum, maximum
前驱,后继 successor, predecessor
上界,下界 floor, ceil
某个元素的排名 rank
寻找第k大(小)元素 select

思路

见代码注释

代码

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root == NULL)
        {
            return NULL;
        }

        //p和q在二分搜索树中的左侧,那么在左侧寻找其公共祖先
        if(p->val < root->val&& q->val < root->val)
        {
            return lowestCommonAncestor(root->left,p,q);
        }
        //p和q在二分搜索树中的右侧,那么在右侧寻找其公共祖先
        if(p->val > root->val&& q->val > root->val)
        {
            return lowestCommonAncestor(root->right,p,q);
        }

        //若不然,不是上述的两种情况,一个是>=root值,一个是<=root值,这种情况下
        //p,q的公共祖先是root,含有二种情况
        //1.p<root ,q>root    即p和q在root的两侧
        //2.p=root或者q=root
        //注意  p和q能否都在树上,p和q的有效性  
        return root;

    }
};

结果

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值