fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  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. // this is same as bfs
  17.  
  18. Node* buildTree(){
  19.  
  20. queue<Node*>q;
  21.  
  22. int d;cin>>d;
  23.  
  24. // if -1 return null
  25.  
  26. if(d==-1)return NULL;
  27.  
  28. // else make node and push to queue
  29.  
  30. Node*head=new Node(d);
  31.  
  32. q.push(head);
  33.  
  34. int lc,rc;
  35.  
  36. // now till the queue is not empty pop and push the children if next input is not -1
  37.  
  38. while(!q.empty()){
  39.  
  40. Node*f=q.front();
  41.  
  42. q.pop();
  43.  
  44. cin>>lc>>rc;
  45.  
  46. if(lc!=-1){
  47.  
  48. f->left=new Node(lc);
  49.  
  50. q.push(f->left);
  51.  
  52. }
  53.  
  54. if(rc!=-1){
  55.  
  56. f->right=new Node(rc);
  57.  
  58. q.push(f->right);
  59.  
  60. }
  61.  
  62. }
  63.  
  64. // finally return head
  65.  
  66. return head;
  67. }
  68.  
  69.  
  70. void print_left_side(Node*root, int level, int &maxlevel){
  71. if(root==NULL){
  72. return;
  73. }
  74.  
  75. if(maxlevel<level){
  76. cout<<root->data<<" ";
  77. maxlevel = level;
  78. }
  79.  
  80. print_left_side(root->left, level+1, maxlevel);
  81. print_left_side(root->right, level+1, maxlevel);
  82. }
  83.  
  84.  
  85. int main(){
  86. Node*root = buildTree();
  87. int maxLevel = -1;
  88. int maxLevel2 = -1;
  89. print_left_side(root,0,maxLevel2);
  90. }
Success #stdin #stdout 0.01s 5516KB
stdin
1 2 3 4 5 -1 6 -1 -1 -1 -1 -1 -1
stdout
1 2 4