-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path144.cpp
42 lines (36 loc) · 950 Bytes
/
144.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
// 144. Binary Tree Preorder Traversal - https://leetcode.com/problems/binary-tree-preorder-traversal
#include "bits/stdc++.h"
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution {
private:
vector<int> result;
public:
vector<int> preorderTraversal(TreeNode* root) {
if (root == nullptr) { return result; }
stack<TreeNode*> st;
TreeNode* cur;
st.emplace(root);
while(!st.empty()) {
cur = st.top(); st.pop();
result.emplace_back(cur->val);
if (cur->right) {
st.emplace(cur->right);
}
if (cur->left) {
st.emplace(cur->left);
}
}
return result;
}
};
int main() {
ios::sync_with_stdio(false);
return 0;
}