来自剑指offer
题目:求树中两个结点的最低公共祖先
分析:其实这是一组题目,考官没有说清楚树的结构,那么做法就不尽相同。
比如,如果是二叉排序树的话,我们只需从根结点判断,如果二结点与根的左右子树比较一大一小,那么跟结点就是二者最低公共祖先;如果二结点都比左子结点小,向左子树递归进行比较;如果二结点都比右子树结点大,向右子树递归进行比较;
如果不是二叉排序树,但带有指向父节点的指针,那么此题转换成在两个有相交的链表上求第一个相交点。
如果不带指向父节点的指针,那么我们可以记录从根结点到这两个结点的路径即可求出。代码如下:
#include "stdafx.h"
#include <list>
#include <vector>
#include <iostream>
using namespace std;
struct TreeNode
{
int m_nValue;
list<TreeNode*> m_pChildren;
};
//在以pRoot为根的树中找pNode,如果找到返回true并把路径记录在path中
bool GetNodePath(TreeNode* pRoot, TreeNode* pNode, list<TreeNode*>& path)
{
if (pRoot == pNode)
return true;
path.push_back(pRoot);
bool found = false;
list<TreeNode*>::iterator i = pRoot->m_pChildren.begin();
while (!found && i!=pRoot->m_pChildren.end())
{
found = GetNodePath(*i, pNode, path);
i++;
}
if(!found)
path.pop_back();
return found;
}
//找path1和path2中最后一个相同的结点,作为返回值
TreeNode* GetLastCommonNode(const list<TreeNode*>& path1, const list<TreeNode*>& path2)
{
list<TreeNode*>::const_iterator iterator1 = path1.begin();
list<TreeNode*>::const_iterator iterator2 = path2.begin();
TreeNode* pLast = NULL;
while (iterator1 != path1.end() && iterator2 != path2.end())
{
if (*iterator1 == *iterator2)
pLast = *iterator1;
iterator1++;
iterator2++;
}
return pLast;
}
//方法入口
TreeNode* GetLastCommonParent(TreeNode* pRoot, TreeNode* pNode1, TreeNode* pNode2)
{
if (pRoot==NULL || pNode1==NULL || pNode2==NULL)
return NULL;
list<TreeNode*> path1;
GetNodePath(pRoot,pNode1,path1);
list<TreeNode*> paht2;
GetNodePath(pRoot,pNode2,paht2);
return GetLastCommonNode(path1,paht2);
}
上述方法中,在树中找pNode1和pNode2两个结点需要遍历2次树,不是很高效,其实可以按照深度优先遍历一次找到两个结点的路径。用数组保存下来即可。