-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRani_exp6.cpp
49 lines (40 loc) · 1.01 KB
/
Rani_exp6.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
#include <iostream>
#include <stack>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
void preOrder(TreeNode* root) {
if (root == nullptr)
return;
stack<TreeNode*> stk;
TreeNode* current = root;
while (current != nullptr || !stk.empty()) {
while (current != nullptr) {
cout << current->val << " ";
stk.push(current);
current = current->left;
}
current = stk.top();
stk.pop();
current = current->right;
}
}
TreeNode* newNode(int val) {
TreeNode* node = new TreeNode(val);
return node;
}
int main() {
TreeNode* root = newNode(1);
root->right = newNode(2);
root->right->right = newNode(5);
root->right->right->left = newNode(3);
root->right->right->left->right = newNode(4);
root->right->right->right = newNode(6);
cout << "Preorder Traversal: ";
preOrder(root);
return 0;
}