Skip to content

Commit 83dc486

Browse files
author
weiy
committed
lowest common ancestor of a binary search tree easy
1 parent 22f4e78 commit 83dc486

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
"""
2+
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
3+
4+
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).”
5+
6+
Given binary search tree: root = [6,2,8,0,4,7,9,null,null,3,5]
7+
8+
_______6______
9+
/ \
10+
___2__ ___8__
11+
/ \ / \
12+
0 _4 7 9
13+
/ \
14+
3 5
15+
Example 1:
16+
17+
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
18+
Output: 6
19+
Explanation: The LCA of nodes 2 and 8 is 6.
20+
Example 2:
21+
22+
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
23+
Output: 2
24+
Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself
25+
according to the LCA definition.
26+
Note:
27+
28+
All of the nodes' values will be unique.
29+
p and q are different and both values will exist in the BST.
30+
31+
32+
给定一颗 BST,找到两个子节点的最小公共祖先。
33+
用普通的树的方法也是可以的,不过可以做个剪枝优化。
34+
35+
因为 BST 我们知道每个节点的左右子节点的范围。
36+
37+
1. 如果处于 root 左右,那么直接返回即可。
38+
2. 如果都小于,那么去找左子树。
39+
3. 如果都大,那么去找右子树。
40+
41+
在寻找过程中,
42+
4. 只要有一个命中了,那么直接返回当前节点即可。因为剩下的那个节点只有可能在它的子树中,如果不在它的子树中也不会执行到这一步。
43+
44+
beat 99%
45+
46+
测试地址:
47+
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/
48+
49+
"""
50+
# Definition for a binary tree node.
51+
# class TreeNode(object):
52+
# def __init__(self, x):
53+
# self.val = x
54+
# self.left = None
55+
# self.right = None
56+
57+
class Solution(object):
58+
def lowestCommonAncestor(self, root, p, q):
59+
"""
60+
:type root: TreeNode
61+
:type p: TreeNode
62+
:type q: TreeNode
63+
:rtype: TreeNode
64+
"""
65+
66+
if p.val == root.val or q.val == root.val:
67+
return root
68+
69+
if p.val < root.val and q.val > root.val:
70+
return root
71+
elif p.val > root.val and q.val < root.val:
72+
return root
73+
74+
if p.val > root.val and q.val > root.val:
75+
76+
return self.lowestCommonAncestor(root.right, p, q)
77+
78+
else:
79+
return self.lowestCommonAncestor(root.left, p, q)
80+

0 commit comments

Comments
 (0)