-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathBinaryTreePostorderTraversal.cpp
61 lines (56 loc) · 1.17 KB
/
BinaryTreePostorderTraversal.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
#include "LeetCode.h"
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/* Recursive solution */
class Solution {
public:
vector<int> result;
void pt(TreeNode* root) {
if (root == NULL) return;
pt(root->left);
pt(root->right);
result.push_back(root->val);
}
vector<int> postorderTraversal(TreeNode *root) {
result.clear();
pt(root);
return result;
}
};
/* None recursize solution */
class Solution {
public:
struct Node {
TreeNode* val;
int pc;
Node(TreeNode* v) : val(v), pc(0) {}
};
vector<int> postorderTraversal(TreeNode *root) {
vector<int> result;
stack<Node> node;
node.push(Node(root));
while(!node.empty()) {
Node& t = node.top();
if (t.val == NULL) {
node.pop();
} else if (t.pc == 0) {
node.push(Node(t.val->left));
t.pc++;
} else if (t.pc == 1) {
node.push(Node(t.val->right));
t.pc++;
} else {
result.push_back(t.val->val);
node.pop();
}
}
return result;
}
};