This method exploits the properties of a BST. The idea is to traverse the tree starting from the root. If both p and q are greater than the current node, then the LCA lies in the right subtree. If both are smaller, then it lies in the left subtree. Otherwise, the current node is the LCA.
Time Complexity: O(h), where h is the height of the tree.
Space Complexity: O(h) due to the recursion stack.
1public class Solution {
2 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
3 if (root == null) return null;
4 if (p.val > root.val && q.val > root.val)
5 return lowestCommonAncestor(root.right, p, q);
6 else if (p.val < root.val && q.val < root.val)
7 return lowestCommonAncestor(root.left, p, q);
8 else
9 return root;
10 }
11}
This Java code applies recursion along with BST properties to determine the LCA. Recursive calls are made based on where p and q are located in relation to the current node.
Instead of recursion, this method uses a while loop to traverse the tree. Starting from the root, check if both nodes are greater or smaller than the current node to decide whether to proceed to the right or left subtree respectively. If neither, we've found the LCA.
Time Complexity: O(h), where h is the height of the tree.
Space Complexity: O(1) since it does not use extra space beyond variables.
1public class Solution {
2 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
3 TreeNode current = root;
4 while (current != null) {
5 if (p.val > current.val && q.val > current.val) {
6 current = current.right;
7 } else if (p.val < current.val && q.val < current.val) {
8 current = current.left;
9 } else {
10 return current;
11 }
12 }
13 return null;
14 }
15}
This Java solution applies an iterative approach with a while loop to navigate the BST and determine the LCA using conditions based on values.