标签:ret sicily i++ root blog std print turn str
#include<bits/stdc++.h> using namespace std; struct Node{ int val; Node *left; Node *right; Node(){ val = 0; left = NULL; right = NULL; } }arr[200000]; void insert(Node *root, int a){ if(a > root->val){ if(root->right != NULL){ insert(root->right, a); } else{ Node* next = new Node; next->val = a; root->right = next; return; } } else{ if(root->left != NULL){ insert(root->left, a); } else{ Node *next = new Node; next->val = a; root->left = next; return; } } } void inOrder(Node *root){ if(root->left != NULL){ inOrder(root->left); } printf(" %d", root->val); if(root->right != NULL){ inOrder(root->right); } } void preOrder(Node *root){ printf(" %d", root->val); if(root->left != NULL){ preOrder(root->left); } if(root->right != NULL){ preOrder(root->right); } } void posOrder(Node *root){ if(root->left != NULL){ posOrder(root->left); } if(root->right != NULL){ posOrder(root->right); } printf(" %d", root->val); } void init(int n){ for(int i = 0; i < n+1; i++){ arr[i].val = 0; arr[i].left = arr[i].right = NULL; } } int main(){ int n; int first = 1; while(cin >> n){ int a; init(n); if(n > 0){ scanf("%d", &arr[0].val); arr[0].left = arr[0].right = NULL; } for(int i = 1; i < n; i++){ scanf("%d", &a); arr[i].val = a; arr[i].left = arr[i].right = NULL; Node *tmp = &arr[0]; Node *last; while(tmp != NULL){ last = tmp; if(a > tmp->val){ tmp = tmp->right; } else{ tmp = tmp->left; } } if(a > last->val){ last->right = &arr[i]; } else{ last->left = &arr[i]; } } if(first == 1){ first = 0; } else{ cout << endl; } printf("Inorder:"); if(arr[0].val != 0)inOrder(&arr[0]); printf("\n"); printf("Preorder:"); if(arr[0].val != 0)preOrder(&arr[0]); printf("\n"); printf("Postorder:"); if(arr[0].val != 0)posOrder(&arr[0]); printf("\n"); } }
Sicily 1310:Right-Heavy Tree(二叉搜索树)
标签:ret sicily i++ root blog std print turn str
原文地址:http://www.cnblogs.com/Vincent-Bryan/p/6759660.html