Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 14b6e53

Browse files
马力马力
马力
authored and
马力
committed
Add C++ implementation
Signed-off-by: 马力 <mali0921@HPCL202007007deMacBook-Pro.local>
1 parent eb736e2 commit 14b6e53

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
/**
6+
* Definition for a binary tree node.
7+
* struct TreeNode {
8+
* int val;
9+
* TreeNode *left;
10+
* TreeNode *right;
11+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
12+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
13+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
14+
* };
15+
*/
16+
class Solution {
17+
public:
18+
vector<int> preorderTraversal(TreeNode* root) {
19+
vector<int> res;
20+
stack<TreeNode *> stk;
21+
while (!stk.empty() || root != nullptr) {
22+
if (root != nullptr) {
23+
res.push_back(root->val);
24+
stk.push(root);
25+
root = root->left;
26+
} else {
27+
root = stk.top();
28+
stk.pop();
29+
root = root->right;
30+
}
31+
}
32+
return res;
33+
}
34+
};
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
/**
6+
* Definition for a binary tree node.
7+
* struct TreeNode {
8+
* int val;
9+
* TreeNode *left;
10+
* TreeNode *right;
11+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
12+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
13+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
14+
* };
15+
*/
16+
class Solution {
17+
public:
18+
vector<int> postorderTraversal(TreeNode* root) {
19+
vector<int> res;
20+
stack<pair<TreeNode *, TreeNode *>> stk;
21+
while (!stk.empty() || root != nullptr) {
22+
if (root != nullptr) {
23+
stk.push(make_pair(root, root->right));
24+
root = root->left;
25+
} else {
26+
if (stk.top().second != nullptr) {
27+
// Into right
28+
root = stk.top().second;
29+
stk.top().second = nullptr;
30+
} else {
31+
// True backtracing
32+
res.push_back(stk.top().first->val);
33+
stk.pop();
34+
root = nullptr;
35+
}
36+
}
37+
}
38+
return res;
39+
}
40+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /