//1 在二元树中找出和为某一值的所有路径
#include<iostream>
#include<vector>
using namespace std;
struct BSTreeNode
{
int m_nValue; // value of node
BSTreeNode *m_pLeft; // left child of node
BSTreeNode *m_pRight; // right child of node
};
void addTree(BSTreeNode*&root,int value)
{
if (NULL == root)
{
BSTreeNode *tmp = new BSTreeNode();
tmp->m_nValue = value;
tmp->m_pLeft = NULL;
tmp->m_pRight = NULL;
root = tmp;
}
if (root->m_nValue > value)
return addTree(root->m_pLeft, value);
if (root->m_nValue < value)
return addTree(root->m_pRight, value);
}
void findPath(BSTreeNode*root, int sum, vector<int>&path, int ¤t)
{
if (NULL == root)
return;
current += root->m_nValue;
path.push_back(root->m_nValue);
bool flage = ((!root->m_pLeft) && (!root->m_pRight));
if (flage&¤t == sum)
{
vector<int>::iterator itr = path.begin();
for (; itr != path.end(); ++itr)
cout << *itr << " ";
cout << endl;
}
if (root->m_pLeft)
findPath(root->m_pLeft, sum, path, current);
if (root->m_pRight)
findPath(root->m_pRight, sum, path, current);
current -= root->m_nValue;
path.pop_back();
}
void inorder(BSTreeNode*root)
{
if (root == NULL)
return ;
cout << root->m_nValue << " ";
inorder(root->m_pLeft);
inorder(root->m_pRight);
}
int main()
{
BSTreeNode *root = NULL;
addTree(root, 10);
addTree(root, 12);
addTree(root, 5);
addTree(root, 7);
addTree(root, 4);
inorder(root);
cout << endl;
vector<int>path;
int sum;
int count = 0;
findPath(root, 22, path, count);
system("pause");
return 0;
}