-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy path145-二叉树的后序遍历.cpp
47 lines (47 loc) · 1.17 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
/**
* 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> answer;
vector<int> postorderTraversal(TreeNode * root) {
if(root!=NULL)
{
if(root->left!=NULL)
postorderTraversal(root->left);
if(root->right!=NULL)
postorderTraversal(root->right);
answer.push_back(root->val);
}
return answer;
}
*/
//非递归实现
vector<int> postorderTraversal(TreeNode * root) {
//按根-右-左访问,最后倒序
vector<int> result;
if (root == NULL)
return result;
stack<TreeNode*> s;
s.push(root);
while (!s.empty())
{
TreeNode* temp = s.top();
s.pop();
result.push_back(temp->val);
if(temp->left)
s.push(temp->left);
if(temp->right)
s.push(temp->right);
}
reverse(result.begin(), result.end());
return result;
}
};