fork download
  1. #include <iostream>
  2. #include<queue>
  3. using namespace std;
  4. class node {
  5. public:
  6. int data;
  7. node* left;
  8. node* right;
  9. node(int d) {
  10. data = d;
  11. left = NULL;
  12. right = NULL;
  13. }
  14. };
  15.  
  16. node* buildTree(){
  17. queue<node*>q;
  18. int d;cin>>d;
  19. if(d==-1)return NULL;
  20. node*head=new node(d);
  21. q.push(head);
  22. int lc,rc;
  23. while(!q.empty()){
  24. node*f=q.front();
  25. q.pop();
  26. cin>>lc>>rc;
  27. if(lc!=-1){
  28. f->left=new node(lc);
  29. q.push(f->left);
  30. }
  31. if(rc!=-1){
  32. f->right=new node(rc);
  33. q.push(f->right);
  34. }
  35. }
  36. return head;
  37. }
  38.  
  39. void printPreOrder(node* &root){
  40. if(root==NULL)return;
  41. cout<<root->data<<" ";
  42. printPreOrder(root->left);
  43. printPreOrder(root->right);
  44. }
  45.  
  46. int main()
  47. {
  48. node*root=buildTree();
  49. printPreOrder(root);
  50. }
  51.  
Success #stdin #stdout 0.01s 5312KB
stdin
1 2 3 4 5 -1 6 -1 -1 -1 -1 -1 -1
stdout
1 2 4 5 3 6