用两个指针分别标记从根节点去往这两个结点路径,根据BST的性质,同时向下搜索。当两条路径出现分岔时,出现分岔的这个结点即为最近公共祖先。
/**
* 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) {
TreeNode* pPath, *qPath, *anscester;
pPath = qPath = anscester = root;
while(true){
if(p->val < pPath->val)
pPath = pPath->left;
else if(p->val > pPath->val)
pPath = pPath->right;
if(q->val < qPath->val)
qPath = qPath->left;
else if(q->val > qPath->val)
qPath = qPath->right;
if(pPath == qPath) anscester = pPath;
if(pPath != qPath) break;
}
return anscester;
}
};
时间复杂度:平均,即树高
空间复杂度: