Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- typedef struct TreeNode{
- int val;
- TreeNode *left,*right;
- TreeNode(int v){
- val=v;
- left=right=NULL;
- }
- }TreeNode;
- typedef struct ListNode{
- TreeNode* val;
- ListNode* next;
- ListNode(TreeNode* v){
- val=v;
- next=NULL;
- }
- }ListNode;
- typedef struct Hash{
- ListNode *head,*tail;
- Hash(){
- head=tail=NULL;
- }
- }Hash;
- Hash ar[100];
- int level;
- TreeNode* insert(TreeNode* root,int v){
- if(root==NULL){
- return root=new TreeNode(v);
- }
- if(root->val<v){
- root->right=insert(root->right,v);
- }
- else root->left=insert(root->left,v);
- return root;
- }
- void add(ListNode** head,ListNode** tail,TreeNode* v){
- // printf("%d\n",v->val);
- if(*head==NULL){
- *head=new ListNode((v));
- *tail=*head;
- return;
- }
- (*tail)->next=new ListNode((v));
- *tail=(*tail)->next;
- }
- void rev(TreeNode *root){
- if(root==NULL){
- return;
- }
- int co;
- add(&ar[0].head,&ar[0].tail,root);
- ++level;
- while(1){
- co=0;
- for(ListNode* t=ar[level-1].head;t;t=t->next){
- if(t->val->left){
- add(&ar[level].head,&ar[level].tail,t->val->left);
- ++co;
- }
- if(t->val->right){
- add(&ar[level].head,&ar[level].tail,t->val->right);
- ++co;
- }
- }
- if(co==0){
- break;
- }
- // printf("%d\n",level);
- ++level;
- }
- return;
- }
- void print(ListNode* head){
- for(;head;head=head->next){
- printf("%d ",head->val->val);
- }
- printf("\n");
- return;
- }
- void CLR(){
- for(int i=0;i<100;++i){
- ar[i].head=ar[i].tail=NULL;
- }
- return;
- }
- int main(){
- level=0;
- // CLR();
- int n;
- cin>>n;
- TreeNode* root=NULL;
- for(int i=0;i<n;++i){
- int x;
- cin>>x;
- root=insert(root,x);
- }
- rev(root);
- for(int i=level-1;i>=0;--i){
- print(ar[i].head);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment