235. Lowest Common Ancestor of a Binary Search Tree
Hint - Recursion
/**
* 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)
{
// If both p and q are less than root's value, then LCA must be in the left subtree
// If both p and q are greater than root's value, then LCA must be in the right subtree
// If p and q are on different sides of root, or one of them is the root, then root is the LCA
}
};
- Recursion
/**
* 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)
{
if (p->val < root->val && q->val < root->val)
{
return lowestCommonAncestor(root->left, p, q);
}
if (p->val > root->val && q->val > root->val)
{
return lowestCommonAncestor(root->right, p, q);
}
return root;
}
};
- T:
- S:
Hint - Iteration
/**
* 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)
{
// Start with the root node
// Loop until we find the lowest common ancestor
while ()
{
// Get the value of the current node
// If both p and q are greater than parentVal, LCA must be in the right subtree
if ()
{
}
// If both p and q are less than parentVal, LCA must be in the left subtree
else if ()
{
}
// If p and q are on different sides of the current node, or one of them is the current node,
// then the current node is the lowest common ancestor
else
{
}
}
// This line is never reached because the loop always returns a node
}
};
- Iteration
/**
* 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)
{
TreeNode* node = root;
while (true)
{
int parentVal = node->val;
if (parentVal < p->val && parentVal < q->val)
{
node = node->right;
}
else if (parentVal > p->val && parentVal > q->val)
{
node = node->left;
}
else
{
return node;
}
}
return node;
}
};
- T:
- S: