求解二叉樹深度以及節點數
#define max 30 #define NULL 0 #include"stdlib.h" #include "stdio.h" int countnode; int countleaf; typedef struct btnode { char data; struct btnode *lchild,*rchild; }bttree; bttree *cre_tree(char *str,int i,int m){ bttree *p; if(i>=m){ return NULL; } p=(bttree*)malloc(sizeof(bttree)); p->data=str[i]; p->lchild=cre_tree(str,2*i+1,m); p->rchild=cre_tree(str,2*i+2,m); //建立左右子樹 return p; }
void preorder(bttree *t) { //先序遍歷二叉樹 if(t!=NULL){ printf("%C",t->data);//遍歷存根點 if(t->lchild){ printf("->"); preorder(t->lchild);//遍歷左子樹 } } if(t->rchild){ printf("->"); preorder(t->rchild);//遍歷右子樹 } }
bttree *swap(bttree *p){ //將P指標指向的二叉樹中左右子樹互換 bttree *stack[max]; int k; k=0; stack[k]=0; if(p!=NULL){ stack[++k]=p->lchild; p->lchild=p->rchild; p->rchild=stack[k]; p->lchild=swap(p->lchild); p->rchild=swap(p->rchild); } return p; } //求解點數和葉子節點數 void inordercount(bttree *p){ if(p!=NULL){ countnode++;//統計節點 inordercount(p->lchild); //printf("%c",p->data); if(p->lchild==NULL&&p->rchild==NULL){ countleaf++; } inordercount(p->rchild); //printf("%3d",p->data); } }
int treedeep(bttree *p)//求二叉樹深度、 { int ldeep,rdeep,deep; if(p==NULL){ deep=0; } else{ ldeep=treedeep(p->lchild); rdeep=treedeep(p->rchild); deep=(ldeep>rdeep?ldeep: rdeep)+1; } return deep; }
int main(){ int i,n; char str[max]; bttree *root;//root為指向根節點的指標 printf("請輸入節點數"); scanf("%d",&n); getchar(); printf("請輸入字串長度為:%d\n",n); for(i=0;i<n;i++){ str[i]=getchar(); } printf("\n\n"); root=cre_tree(str,0,n); printf("二叉樹已經建立"); printf("\n"); printf("先序遍歷輸出結果:"); preorder(root); printf("\n"); root=swap(root); printf("交換後先序遍歷輸出結果:"); preorder(root); printf("\n"); printf("輸出完成");// inordercount(root);//計算節點數,葉子節點數 printf("\n 節點數:%d 葉子節點數:%d",countnode,countleaf);//node??? printf("\n"); printf("二叉樹深度為:%d",treedeep(root)); }