#include <iostream>
#include <cstdio>
#include <queue>
#include <stack>
#include <vector>
#include <iterator>
using namespace std;
struct BinaryTreeNode
{
BinaryTreeNode *left;
BinaryTreeNode *right;
int m_value;
int sum;
vector<int> s;
};
queue<BinaryTreeNode* > q;
queue<BinaryTreeNode* > qf;
void AddTreeNode(BinaryTreeNode *&pCurrentNode, int value)
{
if (pCurrentNode == NULL)
{
BinaryTreeNode *newNode = new BinaryTreeNode();
newNode->m_value = value;
newNode->sum = 0;
newNode->left = NULL;
newNode->right = NULL;
pCurrentNode = newNode;
q.push(pCurrentNode);
}else if (q.front()->left == NULL)
{
AddTreeNode(q.front()->left,value);
}else if (q.front()->right == NULL)
{
AddTreeNode(q.front()->right,value);
q.pop();
}
}
void TravelTree(BinaryTreeNode *pCurrentNode)
{
if (pCurrentNode->left != NULL)
{
TravelTree(pCurrentNode->left);
}
cout<<pCurrentNode->m_value<<endl;
if (pCurrentNode->right != NULL)
{
TravelTree(pCurrentNode->right);
}
}
void FindInTree(BinaryTreeNode *pCurrentNode, int goal)
{
pCurrentNode->sum = pCurrentNode->m_value;
pCurrentNode->s.push_back(pCurrentNode->m_value);
qf.push(pCurrentNode);
while(!qf.empty())
{
if (qf.front()->left != NULL)
{
qf.front()->left->sum = qf.front()->sum + qf.front()->left->m_value;
std::copy(qf.front()->s.begin(), qf.front()->s.end(), std::back_inserter(qf.front()->left->s));
qf.front()->left->s.push_back(qf.front()->left->m_value);
qf.push(qf.front()->left);
}
if (qf.front()->right != NULL)
{
qf.front()->right->sum = qf.front()->sum + qf.front()->right->m_value;
std::copy(qf.front()->s.begin(), qf.front()->s.end(), std::back_inserter(qf.front()->right->s));
qf.front()->right->s.push_back(qf.front()->right->m_value);
qf.push(qf.front()->right);
}
if (qf.front()->sum == goal)
{
cout<<"Find! the road is :";
for (int i = 0; i < qf.front()->s.size()-1; ++i)
{
cout<<qf.front()->s[i]<<"=>";
}
cout<<qf.front()->s[qf.front()->s.size()-1];
cout<<endl;
}
qf.pop();
}
}
int main(int argc, char const *argv[])
{
BinaryTreeNode *root = NULL;
AddTreeNode(root,10);
AddTreeNode(root,5);
AddTreeNode(root,12);
AddTreeNode(root,4);
AddTreeNode(root,7);
AddTreeNode(root,17);
// TravelTree(root);
int v;
cout<<"Please input the value that you want to find: ";
cin>>v;
FindInTree(root, v);
return 0;
}
写复杂了,原来只要求根节点到叶子节点啊;