# 235. Lowest Common Ancestor of a Binary Search Tree(Tree-Easy)

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).”

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.

• 如果p、q都比根节点小，则在左子树中递归查找最低公共祖先节点。
• 如果p、q都比根节点大，则在右子树中递归查找最低公共祖先节点。
• 如果p、q一个比根节点大，一个比根节点小，或者有一个等于根节点，则根节点即为最低公共祖先节点。

Language : cpp

```/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (p->val < root->val && root->val > q->val)
return lowestCommonAncestor(root->left, p, q);
else if (p->val > root->val && root->val < q->val)
return lowestCommonAncestor(root->right, p, q);
else
return root;
}
};```

Language : python

```# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if p.val < root.val > q.val:
return self.lowestCommonAncestor(root.left, p, q)
elif p.val > root.val < q.val:
return self.lowestCommonAncestor(root.right, p, q)
else:
return root```

```# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
while True:
if p.val < root.val > q.val:
root = root.left
elif p.val > root.val < q.val:
root = root.right
else:
return root```

99 篇文章40 人订阅

0 条评论

## 相关文章

8420

8630

6530

7530

### 85. 在二叉查找树中插入节点常规操作

You can assume there is no duplicate values in this tree + node.

24120

### Leetcode 124 Binary Tree Maximum Path Sum

Given a binary tree, find the maximum path sum. For this problem, a path is de...

22190

28540

20850

9730

### 平衡二叉树 AVL树结构详解 [Java实现]

https://blog.csdn.net/zhang6622056/article/details/82698859

26020