-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-tree-postorder-traversal.cpp
More file actions
62 lines (51 loc) · 1.4 KB
/
binary-tree-postorder-traversal.cpp
File metadata and controls
62 lines (51 loc) · 1.4 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
//
// Created by Chenguang Wang on 2024/1/18.
//
// https://leetcode.cn/problems/binary-tree-postorder-traversal/description/
#include <vector>
#include <stack>
#include "TreeNode.h"
using namespace std;
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> result;
traversal(root, result);
return result;
}
void traversal(TreeNode *root, vector<int> &v) {
if (root == nullptr) {
return;
}
traversal(root->left, v);
traversal(root->right, v);
v.push_back(root->val);
}
vector<int> postorderTraversal2(TreeNode *root) {
vector<int> result;
stack<TreeNode *> stack;
if (root != nullptr) {
stack.push(root);
}
while (!stack.empty()) {
TreeNode *node = stack.top();
if (node != nullptr) {
stack.pop();
stack.push(node); // 中
stack.push(nullptr);
if (node->right) {
stack.push(node->right); // 右
}
if (node->left) {
stack.push(node->left); // 左
}
} else {
stack.pop();
node = stack.top();
stack.pop();
result.push_back(node->val);
}
}
return result;
}
};