二叉树的知识点 发表于 2017-09-10 | 分类于 C语言 typedef struct node{ ElemType data; struct node leftchild; struct node rightchild;}tree; /创建/12345678910111213void creat(tree *&t){ ElemType data; data=getchar(); if(data=='#') t=NULL; else{ t=(tree *)malloc(sizeof(tree)); t->data=data; creat(t->leftchild); creat(t->righthcild); }} /遍历/1234567891011121314151617181920212223242526272829void preordertraverse(tree *t){ if(t) { printf("%c",t->data); preordertraverse(t->leftchild); preordertraverse(t->rightchild); }}void inordertraverse(tree *t){ if(t) { inordertraverse(t->leftchild); printf("%c",t->data); inordertraverse(t->rightchild); }}void posordertraverse(tree *t){ if(t) { posordertraverse(t->leftchild); posordertraverse(t->rightchild); printf("%c",t->data); }} /二叉树的深度/12345678910111213in depthoftree(tree *t){ int leftdepth; int rightdepth; if(!t) { return 0; } leftdepth=depthoftree(tree->leftchild); rightdepth=depthoftree(tree->rightchild); return (leftdepth>=rightdepth)?(leftdepth+1):(rightdepth+1);} /二叉树的节点的个数/12345678910111213int leafcount(tree *t,int num){ if(t) { if(!t->leftchild&&!t->rightchild) num++; leafcount(t->leftchild); leafcount(t->rightchild); } return num;} /求另一种遍/1234567891011121314151617181920212223struct node *ans(int len,char *st1,char *st2){ tree *root; int i; if(len==0) { return NULL; } root=(struct node *)malloc(sizeof(struct node)); root->data=st1[0]; for(i=0;i<len;i++) { if(st2[i]==root->data) { break; } } root->leftchild=ans(i,st1+1,st2); root->rightchild=ans(len-i-1,st1+i+1,st2+i+1); return root;};