[LeetCode] Binary Tree Preorder Traversal

144. Binary Tree Preorder Traversal

Given the root of a binary tree, return the preorder traversal of its nodes’ values.

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
/**
* 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 Solution {
void preorder(TreeNode* node, vector<int>& res) {
if(!node) return;
res.push_back(node->val);
preorder(node->left, res);
preorder(node->right, res);
return;
}
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
vector<TreeNode*> st{root};
while(!st.empty()) {
auto node = st.back(); st.pop_back();
if(!node) continue;
res.push_back(node->val);
st.push_back(node->right);
st.push_back(node->left);
}
//preorder(root, res);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/18/PS/LeetCode/binary-tree-preorder-traversal/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.