思路:当用前序遍历的方式访问到某一个节点的时候,我们把该节点添加到路径中。如果该节点的值和我们要找的值相等,则打印路径,如果不相等,则继续访问它的子节点。当前节点访问结束之后,递归函数将自动回到它的父节点。因此我们在函数退出之前要在路径上删除当前节点,以确保返回父节点时路径刚好是从根节点到父节点的路径。
下面是寻找根节点到某一特定子节点路径的代码:
//寻找某一个特定的子节点
void findPath(BinaryTreeNode*pRoot,vector<int>&path,int nToFind){
if (pRoot==NULL)
{
return;
}
path.push_back(pRoot->m_nValue);
if (pRoot->m_nValue==nToFind) //达到了子节点
{
printPath(path);
return; //找到了就返回,不需要再找了
}
if (pRoot->m_pLeft != NULL)//左子树
{
findPath(pRoot->m_pLeft, path,nToFind);
}
if (pRoot->m_pRight != NULL)//右子树
{
findPath(pRoot->m_pRight, path,nToFind);
}
path.pop_back();//在返回到父节点之前,在路径上删除当前节点
}
下面是打印path的代码:
//打印路径
void printPath(vector<int>&path){
vector<int>::const_iterator iter = path.begin(); //打印出来
for (; iter != path.end()-1; ++iter)
cout << *iter << "->";
cout << *iter;
cout << endl;//换行
}
以上代码没有直接使用STL中的stack的原因是在stack中只能得到栈顶的元素,而我们打印路径的时候需要得到路径上的所有的点,因此实现代码的时候std::stack不是最好的选择!
//找到所有路径
void findAllPath(BinaryTreeNode*pRoot, vector<int>&path){
if (pRoot == NULL)
{
return;
}
path.push_back(pRoot->m_nValue);
if (pRoot->m_pLeft == NULL&&pRoot->m_pRight == NULL) //达到了叶子节点
{
printPath(path);//打印路径
}
if (pRoot->m_pLeft!=NULL)//左子树
{
findAllPath(pRoot->m_pLeft, path);
}
if (pRoot->m_pRight!=NULL)//右子树
{
findAllPath(pRoot->m_pRight, path);
}
path.pop_back();//在返回到父节点之前,在路径上删除当前节点
}
当然,如果我们需要保存每条路径,那就需要一个额外的vector<vector<int> >用于保存每一条路径,修改后的代码如下:
vector<vector<int> > allPath;
//找到所有路径
void findAllPath(BinaryTreeNode*pRoot, vector<int>&path){
if (pRoot == NULL)
{
return;
}
path.push_back(pRoot->m_nValue);
if (pRoot->m_pLeft == NULL&&pRoot->m_pRight == NULL) //达到了叶子节点
{
printPath(path);//打印路径
allPath.push_back(path);//保存路径
}
if (pRoot->m_pLeft!=NULL)//左子树
{
findAllPath(pRoot->m_pLeft, path);
}
if (pRoot->m_pRight!=NULL)//右子树
{
findAllPath(pRoot->m_pRight, path);
}
path.pop_back();//在返回到父节点之前,在路径上删除当前节点
}
以如下二叉树作为测试二叉树:
以先序的方式构建此二叉树:
//先序创建二叉树
void CreatBTree(BinaryTreeNode *&root)
{
int nValue = 0;
cin >> nValue;
if (-1 == nValue)//-1代表为空
{
return;
}
else
{
root = new BinaryTreeNode();
root->m_nValue = nValue;
CreatBTree(root->m_pLeft);
CreatBTree(root->m_pRight);
}
}
测试代码如下:
int main(){
BinaryTreeNode*T=NULL;
cout << "先序构建二叉树:" << endl;
CreatBTree(T);
cout << endl;
cout << "找到所有根节点到叶子节点的路径:" << endl;
vector<int> path;
findAllPath(T,path);
cout << "打印得到的所有路径:" << endl;
printAllPath(allPath);
path.clear();
int nNode;
while (true)
{
cout << "输入要找的子节点:" << endl;
cin >> nNode;
cout << "根节点到子节点"<<nNode<<"的路径:" << endl;
findPath(T, path, nNode);
cout << endl;
path.clear();//清零
}
return 0;
}
打印所有路径的代码如下:
//打印所有路径
void printAllPath(vector<vector<int> >&path){
for (int i = 0; i < path.size();i++)
{
printPath(path[i]);
}
}
输出结果如下所示: