-
Notifications
You must be signed in to change notification settings - Fork 0
/
145. 二叉树的后序遍历.cc
62 lines (59 loc) · 1.49 KB
/
145. 二叉树的后序遍历.cc
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root)
{
vector<int> res;
if(root == nullptr) return res;
if(root->left)
{
const vector<int> &left = postorderTraversal(root->left);
res = std::move(left);
}
if(root->right)
{
const vector<int> &right = postorderTraversal(root->right);
res.insert(res.end(), right.begin(), right.end());
}
res.push_back(root->val);
return res;
}
};
/* 栈,迭代做法 */
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root)
{
if(root == nullptr) return vector<int>();
deque<int> res;
stack<TreeNode *> s;
s.push(root);
while(!s.empty())
{
TreeNode *node = s.top();
s.pop();
res.insert(res.begin(), node->val);
if(node->left)
{
s.push(node->left);
}
if(node->right)
{
s.push(node->right);
}
}
//vector<int> vec;
//vec.reserve(res.size());
//std::copy(res.begin(), res.end(), std::back_inserter(vec));
//return vec;
return vector<int>(res.begin(), res.end());
}
};