fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define all(v) (v).begin(),(v).end()
  4.  
  5. struct TreeNode{
  6. int data;
  7. TreeNode* left;
  8. TreeNode* right;
  9.  
  10. TreeNode(int val):left(nullptr),right(nullptr),data(val){};
  11. };
  12. vector<int>postOrd(TreeNode* root){
  13. vector<int>post;
  14. if(root == nullptr)return post;
  15.  
  16. stack<TreeNode*>st;
  17. st.push(root);
  18.  
  19. while(!st.empty()){
  20. auto u = st.top();st.pop();
  21.  
  22. post.push_back(u->data);
  23.  
  24. if(u->left){
  25. st.push(u->left);
  26. }
  27.  
  28. if(u->right){
  29. st.push(u->right);
  30. }
  31.  
  32. }
  33. reverse(all(post));
  34. return post;
  35. }
  36. TreeNode* buildTree(){
  37. int x;
  38. cin>>x;
  39. if(x == -1)return nullptr;
  40. TreeNode* root = new TreeNode(x);
  41.  
  42. queue<TreeNode*>q;
  43. q.push(root);
  44.  
  45. while(!q.empty()){
  46. auto u = q.front();q.pop();
  47.  
  48. if(cin>>x && x!=-1 ){
  49. u->left = new TreeNode(x);
  50. q.push(u->left);
  51. }
  52.  
  53. if(cin>>x && x!=-1 ){
  54. u->right = new TreeNode(x);
  55. q.push(u->right);
  56. }
  57. }
  58. return root;
  59. }
  60. int main() {
  61. TreeNode* root = buildTree();
  62. vector<int>post =postOrd(root);
  63. for(int x:post)cout<<x;
  64.  
  65. return 0;
  66. }
Success #stdin #stdout 0s 5320KB
stdin
1 -1 2 3
stdout
321