-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDAY 25 Binary tree preorder trevasrsal.cpp
98 lines (90 loc) · 2.04 KB
/
DAY 25 Binary tree preorder trevasrsal.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
87
88
89
90
91
92
93
94
95
96
97
// Problem 1 binary tree perorder trevarsal .cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *l;
* TreeNode *r;
* TreeNode() : val(0), l(nullptr), r(nullptr) {}
* TreeNode(int x) : val(x), l(nullptr), r(nullptr) {}
* TreeNode(int x, TreeNode *l, TreeNode *r) : val(x), l(l), r(r) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*>st;// stack imput
TreeNode* node=root;
vector<int> inorder; // vector
while(true)
{
if(node!=NULL)
{
st.push(node);
node=node->left;
}
else
{
if(st.empty() == true)
break;
node=st.top();
st.pop();
inorder.push_back(node->val);
node=node->right;
}}
return inorder;
}
};
//problem 2Binary Tree Inorder Traversal.cpp
//
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int>preorder;
if(root==NULL)
return preorder;
stack<TreeNode*>st;
st.push(root);
while(!st.empty())
{
root=st.top();
st.pop();
preorder.push_back(root->val);
if(root->right!=NULL)
{
st.push(root->right);
}
if(root->left!=NULL)
{
st.push(root->left);
}
}return preorder;
}
};
//problem 3 Binary Tree postorder Traversal
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int>postorder;
if(root ==NULL)
return postorder;
stack<TreeNode* >s1,s2;
s1.push(root);
while(!s1.empty())
{
root=s1.top();
s1.pop();
s2.push(root);
if(root->left!=NULL)
s1.push(root->left);
if(root->right!=NULL)
s1.push(root->right);
}
while(!s2.empty())
{
postorder.push_back(s2.top()->val);
s2.pop();
}
return postorder;
}
};