Binary Tree Postorder Traversal:
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
#include<iostream>
#include<vector>
#include<stack>
#define NUM 2
using namespace std;
struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
};
class Solution{
public:
vector<int> postorderTraversal(TreeNode *root)
{
vector<int> data;
stack<TreeNode*> stk;
while(root!=NULL||!stk.empty())
{
if(root)
{
while(root)
{
data.push_back(root->val);
stk.push(root);
root=root->right;
}
}
else
{
root=stk.top()->left;
stk.pop();
}
}
reverse(data.begin(),data.end());
return data;
}
};
int main()
{
TreeNode tree[NUM],*root=NULL,*next=NULL,*head=NULL;
Solution s;
vector<int> ans;
int i;
for(i=0;i<NUM;i++)
cin>>tree[i].val;
root=new TreeNode;
root->val=tree[0].val;
head=root;
i=1;
while(i<NUM)
{
next=new TreeNode;
root->left=next;
root->right=NULL;
next->val=tree[i].val;
root=next;
i++;
}
root->left=root->right=NULL;
root=head;
ans=s.postorderTraversal(root);
vector<int>::iterator it=ans.begin();
while(it!=ans.end())
{cout<<*it<<"\n";it++;}
}