链接
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/#/solutions
题意
给一个BST,求两个节点的LCA
思路
相比于二叉树的LCA就会简单很多,我们只需要从根节点往下走,找到他们俩的分叉点即可。
代码
/**
* 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 (!root) return NULL;
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;
}
};