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]
.
/**
* Definition for binary tree
* 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) {
if(root){
postorderTraversal(root->left);
postorderTraversal(root->right);
values.push_back(root->val);
return values;
}else{
return values;
}
}
private:
vector<int> values;
};
。。。我就说怎么会有这么简单的题,没看到用非递归
非递归:
/**
* Definition for binary tree
* 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) {
stack<TreeNode *> paths;
map<TreeNode *,bool> visited;
while(root || !paths.empty()){
while(root){
paths.push(root);
root=root->left;
}
if(!paths.empty()){
TreeNode *p= paths.top();
while(!paths.empty() && visited[p]){//p的右子树已经访问过了
values.push_back(p->val);
paths.pop();
if(!paths.empty())
p=paths.top();
}
if(!visited[p]){
visited[p]=true;
root=p->right;
};
}
}
return values;
}
private:
vector<int> values;
};