面試題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;
}
};