-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path25_PathInTree.cpp
74 lines (67 loc) · 2.05 KB
/
25_PathInTree.cpp
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
70
71
72
73
74
#include <iostream>
#include <vector>
using namespace std;
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
void FindPathCore(BinaryTreeNode* pRoot, int value, vector<int> &path)
{
if (pRoot->m_pLeft == NULL && pRoot->m_pRight == NULL)
{
if (value == pRoot->m_nValue)
{
path.push_back(pRoot->m_nValue);
for (int i = 0; i < path.size(); i++)
{
cout << path[i] << " ";
}
cout << endl;
path.pop_back();
}
return;
}
int residual = value - pRoot->m_nValue;
path.push_back(pRoot->m_nValue);
if (pRoot->m_pLeft != NULL)FindPathCore(pRoot->m_pLeft, residual, path);
if (pRoot->m_pRight != NULL)FindPathCore(pRoot->m_pRight, residual, path);
path.pop_back();
}
void FindPath(BinaryTreeNode* pRoot, int value)
{
if (pRoot == NULL)
return;
vector<int> path;
FindPathCore(pRoot, value, path);
}
int main()
{
BinaryTreeNode* root1 = new BinaryTreeNode;
root1->m_nValue = 8;
root1->m_pLeft = new BinaryTreeNode;
root1->m_pLeft->m_nValue = 6;
root1->m_pRight = new BinaryTreeNode;
root1->m_pRight->m_nValue = 10;
root1->m_pLeft->m_pLeft = new BinaryTreeNode;
root1->m_pLeft->m_pLeft->m_nValue = 5;
root1->m_pLeft->m_pLeft->m_pLeft = NULL;
root1->m_pLeft->m_pLeft->m_pRight = NULL;
root1->m_pLeft->m_pRight = new BinaryTreeNode;
root1->m_pLeft->m_pRight->m_nValue = 7;
root1->m_pLeft->m_pRight->m_pLeft = NULL;
root1->m_pLeft->m_pRight->m_pRight = NULL;
root1->m_pRight->m_pLeft = new BinaryTreeNode;
root1->m_pRight->m_pLeft->m_nValue = 9;
root1->m_pRight->m_pLeft->m_pLeft = NULL;
root1->m_pRight->m_pLeft->m_pRight = NULL;
root1->m_pRight->m_pRight = new BinaryTreeNode;
root1->m_pRight->m_pRight->m_nValue = 1;
root1->m_pRight->m_pRight->m_pLeft = NULL;
root1->m_pRight->m_pRight->m_pRight = NULL;
FindPath(root1, 19);
FindPath(root1, 21);
FindPath(root1, 29);
return 0;
}