面试题68-2:二叉树的最近公共祖先.
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == NULL || p == NULL || q == NULL) return NULL;
vector<TreeNode*> path1, path2; //双向链表容器list也可以
GetNodePath(root, p, path1);
GetNodePath(root, q, path2);
return GetLastCommonNode(path1, path2);
}
//获取从根节点到目标节点的路径
bool GetNodePath(TreeNode* root, TreeNode* node, vector<TreeNode*>& path){ //此处必须为引用,因为此处没有返回值,改变引用就是改变传进来的path
//先把root节点加入到list中
path.push_back(root);
//找到目标节点
if (root == node) return true;
//标志符found
bool found = false; //也可以用一个一维标记数组,标记已经访问过的节点
if (!found && root->left != NULL) found = GetNodePath(root->left, node, path);
if (!found && root->right != NULL) found = GetNodePath(root->right, node, path);
//如果没有找到,则返回头节点时,删除当前节点
if (!found)
path.pop_back();
return found;
}
//获取共同节点
TreeNode* GetLastCommonNode(vector<TreeNode*> path1, vector<TreeNode*> path2){
TreeNode* pLast = nullptr;
vector<TreeNode*>::iterator it1 = path1.begin();
vector<TreeNode*>::iterator it2 = path2.begin();
while (it1!=path1.end()&&it2!=path2.end()){
if (*it1 == *it2) pLast = *it1;
it1++;
it2++;
}
return pLast;
}
};