-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_tree_postorder_traversal.cpp
78 lines (71 loc) · 1.83 KB
/
binary_tree_postorder_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
74
75
76
77
78
// =====================================================================================
//
// Filename: binary_tree_postorder_traversal.cpp
//
// Description: 145. Binary Tree Postorder Traversal. Given a binary tree, return
// the postorder traversal of its nodes' values. Recursive solution is
// trivial, could you do it iteratively?
//
// Version: 1.0
// Created: 09/06/2019 05:07:02 PM
// Revision: none
// Compiler: g++
//
// Author: Zhu Xianfeng (), [email protected]
// Organization:
//
// =====================================================================================
#include <stdio.h>
#include <stack>
#include <vector>
using namespace std;
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution
{
public:
vector<int> postorderTraversal(TreeNode* root)
{
stack<TreeNode*> nodes;
vector<int> values;
if (root == nullptr)
{
return values;
}
// Traversal strategy: reverse of root -> right -> left
nodes.push(root);
while (!nodes.empty())
{
auto* cur = nodes.top();
nodes.pop();
values.insert(values.begin(), cur->val);
if (cur->left != nullptr)
{
nodes.push(cur->left);
}
if (cur->right != nullptr)
{
nodes.push(cur->right);
}
}
return values;
}
};
int main(int argc, char* argv[])
{
TreeNode* root = nullptr;
auto values = Solution().postorderTraversal(root);
if (values.size() > 0)
{
for (auto val: values)
{
printf("%d ", val);
}
}
return 0;
}