235. Lowest Common Ancestor of a Binary Search Tree

本文介绍如何在二叉搜索树中寻找两节点的最低公共祖先(LCA),提出两种方法:递归与迭代,并详细解释了每种方法的实现思路及代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

s思路:
1. 和236不同的地方是,这棵树是bst, 那么搜索的复杂度就应该是o(height).
2. 先看recursive。从根节点出发,分别去搜索两个节点,但这里搜索不用瞎搜索,需要利用BST的性质,比较p->val,q->val和root->val的关系,决定往左边搜还是右边搜。如果root->val>p->val同时root->val>q->val,说明p,q都在root的左侧,因此把root=root->left;如果root->val< p->val同时root->val < q->val,说明p,q都在root的右侧,因此把root=root->right;如果root->val>p->val同时root->val< q->val,或root->val< p->val同时root->val> q->val说明p,q在root的两侧,说明root就是LCA.
3. 再看iterative. 仿佛就是从root一路比较和p,q的值的关系,决定往左还是往右走,而且每次比较都是逐渐靠近答案,不用走回头路,因此没必要用stack吗?写完代码,确实就是不需要stack.
4. 通过这道题和236题,可以打破思维的这个定式:认为iterative必须要用一个stack,不然都不意思和人打交道,用queue都不行,这个确实是自己给自己不小心就设置了这么一个限制,所以思维应该打破这层束缚,而认识到iterative不但可以用stack,用queue也没错,不用任何数据结构更可以的!
5. iterative用stack是为了做dfs,比如:in-order,pre-order;用queue则是做bfs,保存一层的节点;不用的话,就是这道题,一路往下坚定的走向正确答案,每一层只需尝试一个节点,不走回头路!
6. 思维里的限制越少,想问题就越自由!打破思维的墙,任重道远!

//方法1:recursive。利用bst性质,选branch去尝试,复杂度o(height)
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        //
        if(!root||root==p||root==q) return root;
        if(root->val>p->val&&root->val>q->val)
            return lowestCommonAncestor(root->left,p,q);
        else if(root->val<p->val&&root->val<q->val)
            return lowestCommonAncestor(root->right,p,q);
        return root;
    }
};


//方法2:iterative。一路往下,逐渐离正确答案靠近,每次尝试都是正确的,不会走回头路
//也就是不需要利用stack来穿越不同的层级,也不需要queue,因为每一层只需要遍历一个node,因此没必要用queue来保存同一层的节点!
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        //
        while(root){
            if(root->val>p->val&&root->val>q->val)
                root=root->left;
            else if(root->val<p->val&&root->val<q->val)
                root=root->right;
            else
                return root;
        }
        return root;
    }
};
以下是C#中二叉树的lowest common ancestor的源代码: ```csharp using System; public class Node { public int value; public Node left; public Node right; public Node(int value) { this.value = value; this.left = null; this.right = null; } } public class BinaryTree { public Node root; public BinaryTree() { this.root = null; } public Node LowestCommonAncestor(Node node, int value1, int value2) { if (node == null) { return null; } if (node.value == value1 || node.value == value2) { return node; } Node left = LowestCommonAncestor(node.left, value1, value2); Node right = LowestCommonAncestor(node.right, value1, value2); if (left != null && right != null) { return node; } return (left != null) ? left : right; } } public class Program { public static void Main() { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); Node lca = tree.LowestCommonAncestor(tree.root, 4, 5); Console.WriteLine("Lowest Common Ancestor of 4 and 5: " + lca.value); lca = tree.LowestCommonAncestor(tree.root, 4, 6); Console.WriteLine("Lowest Common Ancestor of 4 and 6: " + lca.value); lca = tree.LowestCommonAncestor(tree.root, 3, 4); Console.WriteLine("Lowest Common Ancestor of 3 and 4: " + lca.value); lca = tree.LowestCommonAncestor(tree.root, 2, 4); Console.WriteLine("Lowest Common Ancestor of 2 and 4: " + lca.value); } } ``` 在上面的代码中,我们定义了一个Node类和一个BinaryTree类。我们使用BinaryTree类来创建二叉树,并实现了一个LowestCommonAncestor方法来计算二叉树中给定两个节点的最近公共祖先。 在LowestCommonAncestor方法中,我们首先检查给定节点是否为null或与给定值之一匹配。如果是,则返回该节点。否则,我们递归地在左子树和右子树上调用LowestCommonAncestor方法,并检查它们的返回值。如果左子树和右子树的返回值都不为null,则当前节点是它们的最近公共祖先。否则,我们返回非null的那个子树的返回值。 在Main方法中,我们创建了一个二叉树,并测试了LowestCommonAncestor方法的几个不同输入。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值