代码:
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode *m_pLeft;
BinaryTreeNode *m_pRight;
};
void FindPath(BinaryTreeNode *pRoot, int nSum, vector<int>& path)
{
if (pRoot == NULL || nSum == 0)
{
return;
}
if (pRoot->m_nValue == nSum && pRoot->m_pLeft == NULL && pRoot->m_pRight == NULL)
{
vector<int>::iterator iter = path.begin();
for (; iter!=path.end(); iter++)
{
cout << *iter << " ";
}
cout << pRoot->m_nValue << endl;
return;
}
path.push_back(pRoot->m_nValue);
if (pRoot->m_pLeft != NULL)
{
FindPath(pRoot->m_pLeft, nSum-pRoot->m_nValue, path);
}
if (pRoot->m_pRight != NULL)
{
FindPath(pRoot->m_pRight, nSum-pRoot->m_nValue, path);
}
path.pop_back();
}
//以先序的方式构建二叉树,输入#表示结点为空
void CreateBinaryTree(BinaryTreeNode *&pRoot)
{
int nNodeValue = 0;
cin >> nNodeValue;
if (-1 == nNodeValue)
{
pRoot = NULL;
return;
}
else
{
pRoot = new BinaryTreeNode();
pRoot->m_nValue = nNodeValue;
CreateBinaryTree(pRoot->m_pLeft);
CreateBinaryTree(pRoot->m_pRight);
}
}
void PrintInOrder(BinaryTreeNode *&pRoot)
{
if (pRoot != NULL)
{
PrintInOrder(pRoot->m_pLeft);
cout << pRoot->m_nValue << " ";
PrintInOrder(pRoot->m_pRight);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
BinaryTreeNode *pRoot = NULL;
CreateBinaryTree(pRoot);
PrintInOrder(pRoot);
cout << endl;
vector<int> path;
FindPath(pRoot, 22, path);
system("pause");
return 0;
}
说明:用vector模拟实现栈的功能,而不是用stack,是因为在输出路径时,需要遍历栈中的元素,而stack只能取栈顶元素,stack不是最好的选择