235. Lowest Common Ancestor of a Binary Search Tree
_______6______
/ \
___2__ ___8__
/ \ / \
0 _4 7 9
/ \
3 5/**
* 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;
}
};Last updated
Was this helpful?