forked from xieqilu/Qilu-leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path25.AscendingTraverseBT.cpp
87 lines (73 loc) · 1.3 KB
/
25.AscendingTraverseBT.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
75
76
77
78
79
80
81
82
83
84
85
86
//traverse a binary tree so that the order returned
//is ordered from smallest to greatest
//use a priority_queue and a stack!
#include <iostream>
#include <queue>
#include <stack>
using namespace std;
struct TreeNode
{
int value;
TreeNode *left;
TreeNode *right;
};
class Finder
{
std::priority_queue<int> Q;
std::stack<int> S;
public:
void ascendingTraverse(TreeNode *root);
void printNodes();
};
void Finder::ascendingTraverse(TreeNode *root)
{
if(root == NULL) return;
Q.push(root->value);
ascendingTraverse(root->left);
ascendingTraverse(root->right);
}
void Finder::printNodes()
{
while(!Q.empty())
{
int temp = Q.top();
S.push(temp);
Q.pop();
}
while(!S.empty())
{
std::cout<<S.top()<<"\n";
S.pop();
}
}
int main (int argc, char *argv[])
{
TreeNode node1;
TreeNode node2;
TreeNode node3;
TreeNode node4;
TreeNode node5;
TreeNode node6;
node1.value=4;
node2.value=3;
node3.value=2;
node4.value=5;
node5.value=6;
node6.value=8;
node1.left = &node2;
node1.right = &node3;
node2.left = &node4;
node2.right = &node5;
node3.left = &node6;
node3.right = NULL;
node4.left = NULL;
node4.right = NULL;
node5.left = NULL;
node5.right = NULL;
node6.right = NULL;
node6.left = NULL;
Finder finder;
finder.ascendingTraverse(&node1);
finder.printNodes();
return 0;
}