-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path144.cpp
More file actions
36 lines (36 loc) · 926 Bytes
/
Copy path144.cpp
File metadata and controls
36 lines (36 loc) · 926 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
34
35
36
// Author: btjanaka (Bryon Tjanaka)
// Problem: (Leetcode) 144
// Title: Binary Tree Preorder Traversal
// Link: https://leetcode.com/problems/binary-tree-preorder-traversal
// Idea:
// Difficulty: medium
// Tags: binary-tree, implementation
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> to_visit;
if (root != nullptr) to_visit.push(root);
while (to_visit.size() > 0) {
TreeNode* curr = to_visit.top();
to_visit.pop();
res.push_back(curr->val);
if (curr->right != nullptr) {
to_visit.push(curr->right);
}
if (curr->left != nullptr) {
to_visit.push(curr->left);
}
}
return res;
}
};