[leetcode]: 235. Lowest Common Ancestor of a Binary Search Tree

本文介绍如何在二叉搜索树中寻找两节点的最低公共祖先(LCA),利用二叉搜索树特性进行高效查找。文章详细分析了算法原理,并提供了实现代码。

1.题目

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).”
这里写图片描述
给一棵二叉搜索树,树上的两个节点v,w,求这两个节点的最低公共祖先
例如,节点2,8的最低公共祖先为6. 节点2,4的最低公共祖先为2.

2.分析

二叉搜索树BST满足,左节点的值<根节点的值<右节点的值。
所以从根节点开始往下搜索,如果:
当前节点值>两个节点的值,转到左子树
当前节点值<两个节点的值,转到右子树
介于两者直接,则找到了最低公共子节点。

题外话:如果不是BST,只是一棵普通的二叉树,那么这个问题就转换为求两个链表的第一个公共节点。分别求从根节点到指定节点的路径,然后找这两条路径的第一个汇合点。

3.代码

TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
    int maxv = p->val > q->val ? p->val : q->val;
    int minv = p->val + q->val - maxv;
    while (root) {
        if (root->val > maxv)
            root = root->left;
        else if (root->val < minv)
            root = root->right;
        else
            return root;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值