题解 | #二叉搜索树的最近公共祖先#
二叉搜索树的最近公共祖先
http://www.nowcoder.com/practice/d9820119321945f588ed6a26f0a6991f
比较基础的写法
class Solution {
public:
int lowestCommonAncestor(TreeNode* root, int p, int q) {
if(min(p, q)<root->val && root->val<max(p, q))
return root->val;
else if(root->val<min(p, q))
return lowestCommonAncestor(root->right, p, q);
else if(root->val>max(p, q))
return lowestCommonAncestor(root->left, p, q);
else if(root->val==p)
return p;
else if(root->val==q)
return q;
return root->val;
}
};