|
| 1 | +{ |
| 2 | +/* C++ program to print nodes of extreme corners |
| 3 | +of each level in alternate order */ |
| 4 | +#include <bits/stdc++.h> |
| 5 | +using namespace std; |
| 6 | +/* A binary tree node has data, pointer to left child |
| 7 | +and a pointer to right child */ |
| 8 | +struct Node |
| 9 | +{ |
| 10 | + int data; |
| 11 | + struct Node *left; |
| 12 | + struct Node *right; |
| 13 | + |
| 14 | + Node(int x){ |
| 15 | + data = x; |
| 16 | + left = NULL; |
| 17 | + right = NULL; |
| 18 | + } |
| 19 | +}; |
| 20 | +/* Function to print nodes of extreme corners |
| 21 | +of each level in alternate order */ |
| 22 | +void printExtremeNodes(Node* root); |
| 23 | +/* Driver program to test above functions*/ |
| 24 | +int main() |
| 25 | +{ |
| 26 | + int t; |
| 27 | + scanf("%d |
| 28 | +", &t); |
| 29 | + while (t--) |
| 30 | + { |
| 31 | + map<int, Node*> m; |
| 32 | + int n; |
| 33 | + scanf("%d |
| 34 | +",&n); |
| 35 | + Node *root = NULL; |
| 36 | + while (n--) |
| 37 | + { |
| 38 | + Node *parent; |
| 39 | + char lr; |
| 40 | + int n1, n2; |
| 41 | + scanf("%d %d %c", &n1, &n2, &lr); |
| 42 | + // cout << n1 << " " << n2 << " " << (char)lr << endl; |
| 43 | + if (m.find(n1) == m.end()) |
| 44 | + { |
| 45 | + parent = new Node(n1); |
| 46 | + m[n1] = parent; |
| 47 | + if (root == NULL) |
| 48 | + root = parent; |
| 49 | + } |
| 50 | + else |
| 51 | + parent = m[n1]; |
| 52 | + Node *child = new Node(n2); |
| 53 | + if (lr == 'L') |
| 54 | + parent->left = child; |
| 55 | + else |
| 56 | + parent->right = child; |
| 57 | + m[n2] = child; |
| 58 | + } |
| 59 | + printExtremeNodes(root); |
| 60 | + cout<<endl; |
| 61 | + } |
| 62 | + return 0; |
| 63 | +} |
| 64 | + |
| 65 | +} |
| 66 | +/*This is a function problem.You only need to complete the function given below*/ |
| 67 | +/* |
| 68 | + A binary tree node has data, pointer to left child |
| 69 | + and a pointer to right child |
| 70 | +struct Node |
| 71 | +{ |
| 72 | + int data; |
| 73 | + Node* left; |
| 74 | + Node* right; |
| 75 | +}; |
| 76 | +*/ |
| 77 | +/* Function to print nodes of extreme corners |
| 78 | +of each level in alternate order */ |
| 79 | +void printExtremeNodes(Node* root) |
| 80 | +{ |
| 81 | + // Your code here |
| 82 | + if(!root) return; |
| 83 | + |
| 84 | + queue<Node *> q; |
| 85 | + q.push(root); |
| 86 | + bool leftToRight = false; |
| 87 | + while(!q.empty()){ |
| 88 | + int q_size = q.size(); |
| 89 | + int nc = q_size; |
| 90 | + while(nc--){ |
| 91 | + Node *top = q.front(); |
| 92 | + if(top->left) |
| 93 | + q.push(top->left); |
| 94 | + if(top->right) |
| 95 | + q.push(top->right); |
| 96 | + q.pop(); |
| 97 | + |
| 98 | + if(leftToRight && nc == q_size -1) |
| 99 | + cout<<top->data<<" "; |
| 100 | + if(!leftToRight && nc == 0) |
| 101 | + cout<<top->data<<" "; |
| 102 | + } |
| 103 | + leftToRight = !leftToRight; |
| 104 | + } |
| 105 | +} |
0 commit comments