LeetCode 235: Lowest Common Ancestor of a Binary Search Tree Solution
Master LeetCode problem 235 (Lowest Common Ancestor of a Binary Search Tree), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
235. Lowest Common Ancestor of a Binary Search Tree
Problem Explanation
Explanation
To find the lowest common ancestor (LCA) of two given nodes in a binary search tree (BST), we can utilize the properties of a BST. The key idea is to traverse the tree starting from the root and search for a node p and a node q such that their values lie within the range of the current node's value. This way, we can determine the LCA by following the path where the values of p and q diverge.
- Start from the root node.
- If both
pandqare greater than the current node's value, move to the right subtree. - If both
pandqare smaller than the current node's value, move to the left subtree. - If the current node's value lies between
pandq, then the current node is the LCA. - Return the LCA node.
The time complexity for this approach is O(h), where h is the height of the tree. In the worst case, the height of a BST can be O(n), where n is the number of nodes in the tree, making the time complexity O(n). The space complexity is O(1) as we are using constant extra space for the algorithm.
Solution Code
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while (root != null) {
if (p.val < root.val && q.val < root.val) {
root = root.left;
} else if (p.val > root.val && q.val > root.val) {
root = root.right;
} else {
return root;
}
}
return null;
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 235 (Lowest Common Ancestor of a Binary Search Tree)?
This page provides optimized solutions for LeetCode problem 235 (Lowest Common Ancestor of a Binary Search Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 235 (Lowest Common Ancestor of a Binary Search Tree)?
The time complexity for LeetCode 235 (Lowest Common Ancestor of a Binary Search Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 235 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 235 in Java, C++, or Python.