Skip to content

Commit c21aa84

Browse files
authored
Create 0094-binary-tree-inorder-traversal.cpp
1 parent e251da2 commit c21aa84

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
#include <stack>
13+
14+
class Solution {
15+
public:
16+
/* Recursive
17+
vector<int> helper(TreeNode* node, vector<int>& path) {
18+
if (node == NULL)
19+
return path;
20+
21+
path = helper(node->left, path);
22+
path.push_back(node->val);
23+
path = helper(node->right, path);
24+
return path;
25+
}
26+
*/
27+
28+
// Iterative
29+
vector<int> inorderTraversal(TreeNode* root) {
30+
stack<TreeNode*> stk;
31+
vector<int> path;
32+
TreeNode* current = root;
33+
34+
while (!stk.empty() || current != NULL) {
35+
while (current != NULL) {
36+
stk.push(current);
37+
current = current->left;
38+
}
39+
TreeNode* node = stk.top();
40+
path.push_back(node->val);
41+
stk.pop();
42+
current = node->right;
43+
}
44+
return path;
45+
}
46+
};

0 commit comments

Comments
 (0)