Skip to content

Commit 66fa44c

Browse files
author
Monique Andrade
committed
Added the iterative solution to codedecks-in#144 - Binary Tree Preorder Traversal
1 parent f62d200 commit 66fa44c

File tree

2 files changed

+29
-11
lines changed

2 files changed

+29
-11
lines changed

.vscode/settings.json

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,5 +55,8 @@
5555
"C_Cpp_Runner.useLeakSanitizer": false,
5656
"C_Cpp_Runner.showCompilationTime": false,
5757
"C_Cpp_Runner.useLinkTimeOptimization": false,
58-
"C_Cpp_Runner.msvcSecureNoWarnings": false
58+
"C_Cpp_Runner.msvcSecureNoWarnings": false,
59+
"files.associations": {
60+
"__locale": "cpp"
61+
}
5962
}

C++/Binary-Tree-Preorder-Traversal.cpp

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,19 +9,34 @@
99
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
1010
* };
1111
*/
12+
//This solution is an interative solution for problem #144 using stack
13+
//Preorder Traversal is root, left, right
1214
class Solution {
1315
public:
1416
vector<int> preorderTraversal(TreeNode* root) {
15-
vector<int> node;
16-
preorder(root, node);
17-
return node;
18-
}
19-
private:
20-
void preorder(TreeNode* root, vector<int>& nodes){
21-
if(root == NULL) return;
17+
vector<int> result;
2218

23-
nodes.push_back(root->val);
24-
preorder(root->left, nodes);
25-
preorder(root->right, nodes);
19+
//if root == nullptr, return empty vector
20+
if (root == NULL) {
21+
return result;
22+
}
23+
24+
stack<TreeNode*> node_stack;
25+
node_stack.push(root);
26+
27+
while (!node_stack.empty()) {
28+
TreeNode* node = node_stack.top();
29+
node_stack.pop(); //pop the top node from the stack
30+
result.push_back(node->val); //add the value to the result vector
31+
32+
if (node->right) {
33+
node_stack.push(node->right); //push right child to the stack if it exists
34+
}
35+
if (node->left) {
36+
node_stack.push(node->left); //push left child to the stack if it exists
37+
}
38+
}
39+
40+
return result;
2641
}
2742
};

0 commit comments

Comments
 (0)