fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. struct TreeNode{
  4. TreeNode* left;
  5. TreeNode*right;
  6. int val;
  7. TreeNode(int val):left(nullptr),right(nullptr),val(val){};
  8. };
  9. void helper(TreeNode* root,vector<int>&in){
  10. if(root == nullptr)return;
  11.  
  12. helper(root->left,in);
  13. in.push_back(root->val);
  14. helper(root->right,in);
  15.  
  16. }
  17. vector<int>inOrd(TreeNode* root){
  18. vector<int>in;
  19. helper(root,in);
  20. return in;
  21. }
  22. TreeNode* buildTree(){
  23. int x;
  24. cin>>x;
  25. if(x==-1)return nullptr;
  26. TreeNode* root = new TreeNode(x);
  27.  
  28. queue<TreeNode*>q;
  29. q.push(root);
  30. while(!q.empty()){
  31. auto u = q.front();
  32. q.pop();
  33.  
  34. if(cin>>x && x!=-1){
  35. u->left = new TreeNode(x);
  36. q.push(u->left);
  37. }
  38.  
  39. if(cin>>x && x!=-1){
  40. u->right = new TreeNode(x);
  41. q.push(u->right);
  42. }
  43. }
  44. return root;
  45. }
  46. int main() {
  47. TreeNode* root = buildTree();
  48. vector<int>ans = inOrd(root);
  49. for(int x : ans)cout<<x<<endl;
  50. return 0;
  51. }
Success #stdin #stdout 0.01s 5316KB
stdin
1 2 3 4 5
stdout
4
2
5
1
3