题目描述:

Given a binary tree, return the postorder traversal of its nodes’ values.

For example: Given binary tree {1,#,2,3},

1
2
3
4
5
6
1
\
2
/
3

return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

非递归后序遍历.

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
/**
* 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> ans;
if(!root) return ans;
vector<TreeNode*> stack = {root};

while(!stack.empty()){
TreeNode* n = stack.back();
stack.pop_back();
ans.push_back(n->val);
if(n->left) stack.push_back(n->left);
if(n->right) stack.push_back(n->right);
}
reverse(ans.begin(), ans.end());

return ans;
}
};