

#include "stdafx.h"
#include
#include
using namespace std;
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode *m_pLeft;
BinaryTreeNode *m_pRight;
};
void FindPath(BinaryTreeNode *pRoot, int nSum, vector& path)
{
if (pRoot == NULL || nSum == 0)
{
return;
}
if (pRoot->m_nValue == nSum && pRoot->m_pLeft == NULL && pRoot->m_pRight == NULL)
{
vector::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 nNodeva lue = 0;
cin >> nNodeva lue;
if (-1 == nNodeva lue)
{
pRoot = NULL;
return;
}
else
{
pRoot = new BinaryTreeNode();
pRoot->m_nValue = nNodeva lue;
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 path;
FindPath(pRoot, 22, path);
system("pause");
return 0;
}