-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_tree_inorder_traversal.cpp
More file actions
93 lines (83 loc) · 2.03 KB
/
binary_tree_inorder_traversal.cpp
File metadata and controls
93 lines (83 loc) · 2.03 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
* =====================================================================================
*
* Filename: binary_tree_inorder_traversal.cpp
*
* Description: 94. Binary Tree Inorder Traversal. Given a binary tree, return the
* inorder traversal of its nodes' values.
*
* Version: 1.0
* Created: 07/09/2019 02:25:44 PM
* Revision: none
* Compiler: gcc
*
* Author: xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stack>
#include <vector>
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
// Recursive
class Solution1
{
public:
std::vector<int> inorderTraversal(TreeNode* root)
{
std::vector<int> values;
inorderTraversal(root, &values);
return values;
}
private:
void inorderTraversal(TreeNode* node, std::vector<int>* values)
{
if (node == nullptr)
{
return;
}
inorderTraversal(node->left, values);
values->push_back(node->val);
inorderTraversal(node->right, values);
}
};
// Non-recursive
class Solution2
{
public:
std::vector<int> inorderTraversal(TreeNode* root)
{
std::vector<int> values;
std::stack<TreeNode*> nodes;
TreeNode* ptr = root;
while (ptr != nullptr || !nodes.empty())
{
while (ptr != nullptr)
{
nodes.push(ptr);
ptr = ptr->left;
}
// Visit current node
ptr = nodes.top();
values.push_back(ptr->val);
ptr = ptr->right;
nodes.pop();
}
return values;
}
};
using Solution = Solution2;
int main(int argc, char* argv[])
{
TreeNode* root = nullptr;
auto values = Solution().inorderTraversal(root);
printf("Size: %ld\n", values.size());
return 0;
}