首页 > 代码库 > Sicily 1310:Right-Heavy Tree(二叉搜索树)
Sicily 1310:Right-Heavy Tree(二叉搜索树)
#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(二叉搜索树)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。