hdu 3999 The order of a Tree(二叉搜索树)
2013-09-05 15:21
465 查看
在做另一道题的时候需要用到二叉搜索树,不过我不了解这种数据结构,所以学习一下。
这道题的话就是建立一个二叉搜索树,然后先序输出。
数组建树:
链表建树:
这道题的话就是建立一个二叉搜索树,然后先序输出。
数组建树:
#include<stdio.h> #include<string.h> #define N 100005 struct node { int x; int lson,rson; } a[N*2]; int cnt; int InsertTree(int t,int x) { if(t==0) { t=cnt++; a[t].lson=0; a[t].rson=0; a[t].x=x; } else { if(x>a[t].x) a[t].rson=InsertTree(a[t].rson,x); else a[t].lson=InsertTree(a[t].lson,x); } return t; } void print(int t) { if(t!=0) { printf(" %d",a[t].x); print(a[t].lson); print(a[t].rson); } return ; } int main() { int n; while(scanf("%d",&n)!=EOF) { int i,t; scanf("%d",&t); a[1].x=t; a[1].lson=0; a[1].rson=0; cnt=2; for(i=2; i<=n; i++) { scanf("%d",&t); InsertTree(1,t); } printf("%d",a[1].x); print(a[1].lson); print(a[1].rson); printf("\n"); } return 0; }
链表建树:
#include<stdio.h> #include<string.h> #include<malloc.h> struct node { int x; node *lson,*rson; }*root; node *InsertTree(node *root,int x) { if(root==NULL) { root=(node *)malloc(sizeof(node)); root->lson=NULL; root->rson=NULL; root->x=x; } else { if(root->x>x) root->lson=InsertTree(root->lson,x); else root->rson=InsertTree(root->rson,x); } return root; } void print(node *root) { if(root!=NULL) { printf(" %d",root->x); print(root->lson); print(root->rson); } return ; } int main() { int n; while(scanf("%d",&n)!=EOF) { int i,x; root=NULL; for(i=1; i<=n; i++) { scanf("%d",&x); root=InsertTree(root,x); } printf("%d",root->x); print(root->lson); print(root->rson); printf("\n"); } return 0; }
相关文章推荐
- HDU3999 The order of a Tree(构建二叉搜索树模板指针)
- HDU 3999 The order of a Tree 二叉搜索树 BST
- HDU 3999 The order of a Tree 二叉搜索树 BST
- 二叉搜索树的前序遍历:hdu 3999 The order of a Tree
- HDU 3999 The order of a Tree (二叉搜索树+先序遍历)
- hdu 3999 The order of a Tree (二叉搜索树)
- 多效第16场 HDU 3999 The order of a Tree(二叉树)
- HDU 3999----The order of a Tree(二叉树的前序遍历)
- The order of a Tree HDU - 3999
- hdu 3999:The order of a Tree
- hdu 3999 The order of a Tree
- hdu 3999 The order of a Tree
- hdu 3999 The order of a Tree
- HDU 3999 The order of a Tree
- HDU 3999 The order of a Tree
- hdu 3999 The order of a Tree
- HDU-3999 The order of a Tree 树的遍历
- hdu 3999 The order of a Tree
- HDU(3999)The order of a Tree
- Hdu 3999 - The order of a Tree