1 bool GetNodePath(TreeNode *pRoot, TreeNode *pNode, list<TreeNode *>&path)
2 {
3 if (pRoot == pNode)
4 return true;
5 path.push_back(pRoot);
6 bool found = false;
7 vector<TreeNode *>::iterator i = pRoot->m_vChildren.begin();
8 while (!found && i < pRoot->m_vChildren.end())
9 {
10 found = GetNodePath(*i, pNode, path);
11 ++i;
12 }
13 if (!found)
14 path.pop_back();
15 return found;
16 }
17
18 TreeNode *GetLastCommonNode(const list<TreeNode*>& path1, const list<TreeNode*>& path2)
19 {
20 list<TreeNode*>::const_iterator iterator1 = path1.begin();
21 list<TreeNode*>::const_iterator iterator2 = path2.begin();
22
23 TreeNode* pLast = NULL;
24
25 while (iterator1 != path1.end() && iterator2 != path2.end())
26 {
27 if (*iterator1 == *iterator2)
28 pLast = *iterator1;
29 iterator1++;
30 iterator2++;
31 }
32 return pLast;
33 }
34
35 TreeNode* GetLastCommonParent(TreeNode* pRoot, TreeNode* pNode1, TreeNode* pNode2)
36 {
37 if (pRoot == NULL || pNode1 == NULL || pNode2 == NULL)
38 return NULL;
39 list<TreeNode*> path1;
40 GetNodePath(pRoot, pNode1, path1);
41
42 list<TreddNode*> path2;
43 GetNodePath(pRoot, pNode1, pNode2);
44
45 return GetLastCommonNode(path1, path2);
46 }