Discription
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
Solution
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (p->val > q->val)
return lowestCommonAncestor(root, q, p);
if (root->val >= p->val && root->val <= q->val)
return root;
else if(root->val>=p->val && root->val >= q->val){
return lowestCommonAncestor(root->left, p, q);
}
else
return lowestCommonAncestor(root->right, p, q);
}
GitHub-Leetcode:https://github.com/wenwu313/LeetCode