思路:由二叉搜索树的性质我们很容易得到从根结点到p和q的路径,那么p和q的最近公共祖先就是从根结点到他们路径上的最后一个相同的结点。
我们从根结点遍历搜索二叉树找到p跟q的路径并记录下来,然后遍历循环路径,找到第一个不相等的点,说明在此时分叉了,那么上一个我们存下来的节点,就是最后一个公有的结点了,即为最近公共祖先。
/**
* 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:
vector<TreeNode*> getPath(TreeNode* root,TreeNode* target){
vector<TreeNode*> path;
TreeNode* head = root;
while(head->val != target->val){
path.push_back(head);
if(head->val < target->val){
head = head->right;
}
else{
head = head->left;
}
}
path.push_back(head);
return path;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
vector<TreeNode*> path_p = getPath(root,p);
vector<TreeNode*> path_q = getPath(root,q);
TreeNode* ans;
for(int i=0;i<path_p.size() && i<path_q.size();i++){
if(path_q[i] == path_p[i]){
ans = path_q[i];
}
else{
break;
}
}
return ans;
}
};