forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0094-binary-tree-inorder-traversal.cpp
46 lines (42 loc) · 1.17 KB
/
0094-binary-tree-inorder-traversal.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
43
44
45
46
/**
* 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) {}
* };
*/
#include <stack>
class Solution {
public:
/* Recursive
vector<int> helper(TreeNode* node, vector<int>& path) {
if (node == NULL)
return path;
path = helper(node->left, path);
path.push_back(node->val);
path = helper(node->right, path);
return path;
}
*/
// Iterative
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> stk;
vector<int> path;
TreeNode* current = root;
while (!stk.empty() || current != NULL) {
while (current != NULL) {
stk.push(current);
current = current->left;
}
TreeNode* node = stk.top();
path.push_back(node->val);
stk.pop();
current = node->right;
}
return path;
}
};