Skip to content

Commit 996d263

Browse files
committed
Add iterative solution for BST LCA
1 parent 569ff3a commit 996d263

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

src/com/andrewbayd/BinarySearchTreeLCA/Solution.java

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,31 @@
11
package com.andrewbayd.BinarySearchTreeLCA;
22

3+
/*
4+
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
5+
6+
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
7+
*/
8+
39
public class Solution {
410

5-
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
11+
public TreeNode lowestCommonAncestorIterative(TreeNode root, TreeNode p, TreeNode q) {
12+
while (root != null) {
13+
if (p.val < root.val && q.val < root.val) {
14+
root = root.left;
15+
} else if (p.val > root.val && q.val > root.val) {
16+
root = root.right;
17+
} else {
18+
return root;
19+
}
20+
}
21+
return root;
22+
}
23+
24+
public TreeNode lowestCommonAncestorRecursive(TreeNode root, TreeNode p, TreeNode q) {
625
if (p.val > root.val && q.val > root.val) {
7-
return lowestCommonAncestor(root.right, p, q);
26+
return lowestCommonAncestorRecursive(root.right, p, q);
827
} else if (p.val < root.val && q.val < root.val) {
9-
return lowestCommonAncestor(root.left, p, q);
28+
return lowestCommonAncestorRecursive(root.left, p, q);
1029
} else {
1130
return root;
1231
}

0 commit comments

Comments
 (0)