-
Notifications
You must be signed in to change notification settings - Fork 0
/
145-二叉树的后序遍历.cpp
49 lines (48 loc) · 1.22 KB
/
145-二叉树的后序遍历.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
/*
* @lc app=leetcode.cn id=145 lang=cpp
*
* [145] 二叉树的后序遍历
*/
// @lc code=start
/**
* 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) {}
* };
*/
class Solution
{
public:
vector<int> postorderTraversal(TreeNode* root)
{
vector<int> result;
vector<TreeNode*> stack;
TreeNode* pre = nullptr;
while (root) {
stack.push_back(root);
root = root->left;
}
while (!stack.empty()) {
auto* top = stack.back();
if (top->right == pre || !top->right) {
result.push_back(top->val);
stack.pop_back();
pre = top;
}
else {
auto* temp = top->right;
while (temp) {
stack.push_back(temp);
temp = temp->left;
}
}
}
return result;
}
};
// @lc code=end