Binary Tree Postorder Traversal
Binary Tree Postorder Traversal
题目
Given a binary tree, return the postorder traversal of its nodes’ values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
思路
后序遍历,利用栈
解题
c++版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/**
* 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> result;
stack<pair<TreeNode*,int>> ss;
ss.push(make_pair(root,0));
while(!ss.empty()){
TreeNode* tmp=ss.top().first;
if(tmp==NULL)
ss.pop();
else{
switch(ss.top().second++){
case 0:
ss.push(make_pair(tmp->left,0));
break;
case 1:
ss.push(make_pair(tmp->right,0));
break;
default:
result.push_back(tmp->val);
ss.pop();
break;
}
}
}
return result;
}
};
Python版1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a list of integers
def postorderTraversal(self, root):
result=[]
self.post1(root,result)
return result
def post1(self,root,result):
if root:
self.post1(root.left,result)
self.post1(root.right,result)
result.append(root.val)