-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindTreePath.cpp
More file actions
69 lines (67 loc) · 1.43 KB
/
FindTreePath.cpp
File metadata and controls
69 lines (67 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
#include <vector>
using namespace std;
typedef struct node
{
int nData;
struct node *left;
struct node *right;
}BSNode,*pTree;
void addBSNode(pTree &pCur,int x) //pCur is reference , value can be dynamic changed
{
if(NULL==pCur) //if tree node is null, create a new node and assigned to pCur,
{
pTree pNode=new BSNode();
pNode->left=NULL;
pNode->right=NULL;
pNode->nData=x;
pCur=pNode;
}else
{
if(pCur->nData>x)
addBSNode(pCur->left,x);
else if(pCur->nData<x)
addBSNode(pCur->right,x);
else //not allow insert the same element
return;
}
}
void FindPath(pTree pNode, int expectedNum,vector<int>& vPath, int &curSum)
{
if(NULL == pNode)
return ;
curSum+=pNode->nData;
vPath.push_back(pNode->nData);
if(curSum==expectedNum && (pNode->left==NULL && pNode->right==NULL))
{
for(vector<int>::iterator iter=vPath.begin();iter!=vPath.end();++iter)
cout<<*iter<<" ";
cout<<endl;
}
if(pNode->left)
FindPath(pNode->left,expectedNum,vPath,curSum);
if(pNode->right)
FindPath(pNode->right,expectedNum,vPath,curSum);
curSum-=pNode->nData;
vPath.pop_back();
}
void printTree(pTree pHead)
{
if(NULL==pHead)
return;
printTree(pHead->left);
cout<<pHead->nData<<endl;
printTree(pHead->right);
}
int main()
{
int a[]={4,5,10,12,7};
pTree pRoot=NULL;
vector<int> path;
int pathNum=0;
for(int i=0;i<5;i++)
addBSNode(pRoot,a[i]);
// printTree(pRoot);
FindPath(pRoot,19,path,pathNum);
return 0;
}