-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0094 - Binary Tree Inorder Traversal.cpp
73 lines (60 loc) · 1.73 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <vector>
#include <stack>
#include <memory>
#include <iostream>
#include <unordered_set>
// 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) {}
};
// iterative solution
// class Solution
// {
// public:
// std::vector<int> inorderTraversal(TreeNode *root)
// {
// std::vector<int> result;
// if (!root) return std::move(result);
// std::stack<TreeNode *> nodes{};
// std::unordered_set<TreeNode *> visited;
// nodes.push(root);
// while (!nodes.empty())
// {
// auto node = nodes.top();
// if (node->left && visited.find(node->left) == visited.end())
// {
// nodes.push(node->left);
// continue;
// }
// nodes.pop();
// result.push_back(node->val);
// if (node->right) nodes.push(node->right);
// visited.insert(node);
// }
// return std::move(result);
// }
// };
// recursive solution (obviously faster)
class Solution
{
void traverse(TreeNode * node, std::vector<int> & result)
{
if (!node) return;
traverse(node->left, result);
result.push_back(node->val);
traverse(node->right, result);
}
public:
std::vector<int> inorderTraversal(TreeNode *root)
{
std::vector<int> result;
traverse(root, result);
return std::move(result);
}
};