-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlc_0145.cpp
More file actions
42 lines (38 loc) · 1015 Bytes
/
lc_0145.cpp
File metadata and controls
42 lines (38 loc) · 1015 Bytes
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
/**
* @file lc_0145.cpp
* @brief https://leetcode-cn.com/problems/binary-tree-postorder-traversal/
* @author YongDu
* @date 2021-09-09
*/
class Solution {
public:
vector<int> result; // 结果集
vector<int> postorderTraversal(TreeNode* root) {
if (nullptr == root)
return result;
#if 0
// 1. 递归版
if(root) {
postorderTraversal(root->left);
postorderTraversal(root->right);
result.emplace_back(root->val);
}
return result;
#endif
// 2. 迭代版
stack<TreeNode*> stk;
TreeNode* node = root;
stk.push(node);
while (!stk.empty()) {
node = stk.top();
stk.pop();
result.emplace_back(node->val);
if (node->left)
stk.push(node->left);
if (node->right)
stk.push(node->right);
}
reverse(result.begin(), result.end());
return result;
}
};