The order of a Tree
HDU - 39994 1 3 4 2
1 3 2 4
代码:
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; typedef struct nodetree { struct nodetree *l,*r;//左右孩子节点 int key;//父亲节点 } tree; tree *root; int b[110000],a[110000]; int c,n; tree *creat(int x)//通过申请空间建立临时指针指向父亲节点 { //动态申请一个空间,用来存放一个节点,并用临时指针t指向这个节点 tree *t=(tree *)malloc(sizeof(tree)); t->l=NULL;//把当前节点的左右孩子节点为空 t->r=NULL; t->key=x; return t; } tree *insert(tree *s,int x) { tree *t; if(s==NULL) { t=creat(x);//调用creat函数创建父亲节点 s=t; //printf("*****\n"); } else//递归调用自己创建左右子树 { if(x>s->key)//按照左小右大规则建立二叉树 { s->r=insert(s->r,x); } else s->l=insert(s->l,x); } return s; } void find(tree *root)//先序遍历 { if(root!=NULL) { if(c<n) { printf("%d ",root->key); c++; } else printf("%d\n",root->key); find(root->l);//先序遍历左子树 find(root->r);//先序遍历右子树 } } int main() { while(~scanf("%d",&n)) { int str[110000]; int len,i; root=NULL; for(i=0;i<n;i++) scanf("%d",&str[i]); for(i=0; i<n; i++) { int num=str[i]; root=insert(root,num);//调用insert函数把各个节点插入树中 //root的值改变 } c=1; find(root); //printf("\n"); } }