File tree Expand file tree Collapse file tree 1 file changed +22
-3
lines changed
src/com/andrewbayd/BinarySearchTreeLCA Expand file tree Collapse file tree 1 file changed +22
-3
lines changed Original file line number Diff line number Diff line change 1
1
package com .andrewbayd .BinarySearchTreeLCA ;
2
2
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
+
3
9
public class Solution {
4
10
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 ) {
6
25
if (p .val > root .val && q .val > root .val ) {
7
- return lowestCommonAncestor (root .right , p , q );
26
+ return lowestCommonAncestorRecursive (root .right , p , q );
8
27
} else if (p .val < root .val && q .val < root .val ) {
9
- return lowestCommonAncestor (root .left , p , q );
28
+ return lowestCommonAncestorRecursive (root .left , p , q );
10
29
} else {
11
30
return root ;
12
31
}
You can’t perform that action at this time.
0 commit comments