-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathPreOrderTraversal.cpp
More file actions
33 lines (29 loc) · 818 Bytes
/
Copy pathPreOrderTraversal.cpp
File metadata and controls
33 lines (29 loc) · 818 Bytes
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
// Problem-Link: https://leetcode.com/problems/binary-tree-preorder-traversal/
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class PreOrderTraversal {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> result;
if (root) st.push(root);
while (st.size() > 0) {
TreeNode* tmp = st.top(); st.pop();
result.push_back(tmp->val);
if (tmp->right) st.push(tmp->right);
if (tmp->left) st.push(tmp->left);
}
return result;
}
};