Skip to content

Commit b31f552

Browse files
committed
add another solution of Lowest Common Ancestor of a Binary Search Tree
1 parent 1733a91 commit b31f552

File tree

1 file changed

+19
-5
lines changed

1 file changed

+19
-5
lines changed
Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,28 @@
11
//lint:file-ignore U1000 Ignore all unused code
22
package main
33

4-
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
5-
if p.Val < root.Val && q.Val < root.Val {
6-
return lowestCommonAncestor(root.Left, p, q)
4+
func lowestCommonAncestorIterative(root, p, q *TreeNode) *TreeNode {
5+
node := root
6+
for node != nil {
7+
if p.Val <= node.Val && node.Val <= q.Val || q.Val <= node.Val && node.Val <= p.Val {
8+
return node
9+
}
10+
if p.Val < node.Val && q.Val < node.Val {
11+
node = node.Left
12+
}
13+
if node.Val < p.Val && node.Val < q.Val {
14+
node = node.Right
15+
}
716
}
17+
return nil
18+
}
819

20+
func lowestCommonAncestorRecursive(root, p, q *TreeNode) *TreeNode {
21+
if p.Val < root.Val && q.Val < root.Val {
22+
return lowestCommonAncestorRecursive(root.Left, p, q)
23+
}
924
if root.Val < p.Val && root.Val < q.Val {
10-
return lowestCommonAncestor(root.Right, p, q)
25+
return lowestCommonAncestorRecursive(root.Right, p, q)
1126
}
12-
1327
return root
1428
}

0 commit comments

Comments
 (0)