235. Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to thedefinition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allowa node to be a descendant of itself).”
For example, the lowest common ancestor (LCA) of nodes2and8is6. Another example is LCA of nodes2and4is2, since a node can be a descendant of itself according to the LCA definition.
Thoughts:
Because of BST, we can decide which branch to to based on values. Two ways to approach this problem:
Iterative, O(1) space : Iteratively traversing down the side on which two nodes reside until the "split" is found.
Recuesive
Iterative:
Code 1
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
while((root->val - p->val) * (root-> val - q->val) > 0)
root = (root-> val) > (p->val)? (root->left): (root-> right);
// =0 means either the current node is a. root is one of {p,q} b. root is the lowest parent of p and q.
return root;
}
};