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