#include <iostream>
#include<vector>
using namespace std;
struct BinaryTreeNode
{
int val;
BinaryTreeNode* left;
BinaryTreeNode* right;
};
void FindThePath(BinaryTreeNode* pRoot, int expectedSum, std::vector<int>& path, int currentSum);
//创建一个二叉树结点
BinaryTreeNode* CreateTreeNode(int val)
{
BinaryTreeNode* pNode = new BinaryTreeNode;
pNode->val = val;
pNode->left = nullptr;
pNode->right = nullptr;
return pNode;
}
//连接结点
void Connect(BinaryTreeNode* pRoot, BinaryTreeNode* left, BinaryTreeNode* right)
{
if (pRoot != nullptr)
{
pRoot->left = left;
pRoot->right = right;
}
}
//释放结点
void DestroyTree(BinaryTreeNode* pRoot)
{
if (pRoot != nullptr)
{
BinaryTreeNode* pLeft = pRoot->left;
BinaryTreeNode* pRight = pRoot->right;
delete pRoot;
pRoot = nullptr;
DestroyTree(pLeft);
DestroyTree(pRight);
}
}
void FindPath(BinaryTreeNode* pRoot, int expectedSum)
{
//判断输入
if (pRoot == nullptr)
return;
//保存当前的和
int currentSum = 0;
std::vector<int> path;
FindThePath(pRoot, expectedSum, path, currentSum);
}
void FindThePath(BinaryTreeNode* pRoot, int expectedSum, std::vector<int>& path, int currentSum)
{
currentSum += pRoot->val;
path.push_back(pRoot->val);
bool leaf=false;
//判断是否叶节点
if (pRoot->left == nullptr&&pRoot->right == nullptr)
leaf = true;
//当和满足时且为叶节点时打印路径
if (currentSum == expectedSum && leaf)
{
printf("A path is Found:");
for (auto iter = path.begin();iter != path.end();++iter)
printf("%d\t", *iter);
printf("\n");
}
//继续判断是否递归左子树、右子树
if (pRoot->left != nullptr)
FindThePath(pRoot->left, expectedSum, path, currentSum);
if (pRoot->right != nullptr)
FindThePath(pRoot->right, expectedSum, path, currentSum);
//最后返回上一层时还要把当前的路径所保存的结点删除
path.pop_back();
}
int main()
{
BinaryTreeNode* pNode1 = CreateTreeNode(1);
BinaryTreeNode* pNode2 = CreateTreeNode(2);
BinaryTreeNode* pNode3 = CreateTreeNode(3);
BinaryTreeNode* pNode4 = CreateTreeNode(4);
BinaryTreeNode* pNode5 = CreateTreeNode(5);
BinaryTreeNode* pNode6 = CreateTreeNode(6);
BinaryTreeNode* pNode7 = CreateTreeNode(7);
BinaryTreeNode* pNode8 = CreateTreeNode(8);
BinaryTreeNode* pNode9 = CreateTreeNode(9);
Connect(pNode1, pNode2, pNode3);
Connect(pNode2, pNode4, pNode5);
Connect(pNode3, pNode6, pNode7);
Connect(pNode4, pNode8, pNode9);
FindPath(pNode1, 10);
DestroyTree(pNode1);
return 0;
}