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).”
Given binary search tree: root = [6,2,8,0,4,7,9,null,null,3,5]

Example 1:
2
8
6
Example 2:
2
4
2
Note:
- All of the nodes' values will be unique.
- p and q are different and both values will exist in the BST.
二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它
或者是一棵空树,
或者是具有下列性质的二叉树:
若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
它的左、右子树也分别为二叉排序树。
https://www.geeksforgeeks.org/lowest-common-ancestor-in-a-binary-search-tree/
We can solve this problem using BST properties.We can recursively traverse the BST from root.
The main idea of the solution is,
while traversing from top to bottom, the first node n we encounter with value between n1 and n2, i.e., n1 < n < n2 or same as one of the n1 or n2, is LCA of n1 and n2 (assuming that n1 < n2).
So just recursively traverse the BST in,
if node’s value is greater than both n1 and n2 then our LCA lies in left side of the node,
if it’s is smaller than both n1 and n2, then LCA lies on right side.
Otherwise root is LCA (assuming that both n1 and n2 are present in BST)
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { TreeNode node; if (root.val > p.val && root.val > q.val) { node = LowestCommonAncestor(root.left, p, q); } else if (root.val < p.val && root.val < q.val) { node = LowestCommonAncestor(root.right, p, q); } else { node = root; } return node; }
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2018-04-19 主表a主表b 从表c中有ab两个表中各一个字段a1,b1 从表d中有ab两个表中各一个字段a2,b2
2016-04-19 歌曲