二叉樹的三大遍歷與求高度和結點
阿新 • • 發佈:2019-01-26
#include<stdio.h> typedef struct Node{ char data; struct Node *LChild; struct Node *RChild; }BiTNode,*BiTree; void CreateBiTree(BiTree *bitree){ char c = getchar(); if(c == '.') (*bitree) = NULL; else { (*bitree) = (BiTree)malloc(sizeof(BiTNode)); (*bitree) ->data = c; CreateBiTree(&((*bitree)->LChild)); CreateBiTree(&((*bitree)->RChild)); } } void PreOrder(BiTree root) { /*先序遍歷二叉樹, root為指向二叉樹(或某一子樹)根結點的指標*/ if(root != NULL){ printf("%c",root->data); /*輸出根節點*/ PreOrder(root->LChild); /*先序遍歷左子樹*/ PreOrder(root->RChild); /*先序遍歷右子樹*/ } } InOrder(BiTree root) /*中序遍歷二叉樹, root為指向二叉樹(或某一子樹)根結點的指標*/ { if (root!=NULL){ InOrder(root ->LChild); /*中序遍歷左子樹*/ printf("%c",root ->data); /*訪問根結點*/ InOrder(root ->RChild); /*中序遍歷右子樹*/ } } void PostOrder(BiTree root) /* 後序遍歷二叉樹,root為指向二叉樹(或某一子樹)根結點的指標*/ { if(root!=NULL){ PostOrder(root ->LChild); /*後序遍歷左子樹*/ PostOrder(root ->RChild); /*後序遍歷右子樹*/ printf("%c",root ->data); /*訪問根結點*/ } } void PreOrder1(BiTree root) /* 先序遍歷輸出二叉樹結點, root為指向二叉樹根結點的指標 */ { if (root!=NULL) { printf("%c",root ->data); /* 輸出根結點 */ PreOrder(root ->LChild); /* 先序遍歷左子樹 */ PreOrder(root ->RChild); /* 先序遍歷右子樹 */ } } void PreOrder2(BiTree root) /* 先序遍歷輸出二叉樹中的葉子結點 , root為指向二叉樹根結點的指標 */ { if (root!=NULL) { if (root ->LChild==NULL && root ->RChild==NULL) printf("%c",root ->data); /* 輸出葉子結點 */ PreOrder(root ->LChild); /* 先序遍歷左子樹 */ PreOrder(root ->RChild); /* 先序遍歷右子樹 */ } } /*採用遞迴演算法,如果是空樹,返回0;如果只有一個結點,返回1;否則為左右子樹的葉子結點數之和。*/ int leaf(BiTree root) { int LeafCount; if(root==NULL) LeafCount =0; else if ((root->LChild==NULL)&&(root->RChild==NULL)) LeafCount =1; else /* 葉子數為左右子樹的葉子數目之和 */ LeafCount =leaf(root->LChild)+leaf(root->RChild); return LeafCount; } int PostTreeDepth(BiTree bt) /* 後序遍歷求二叉樹bt高度的遞迴演算法 */ { int hl, hr, max; if(bt!=NULL) { hl=PostTreeDepth(bt->LChild); /* 求左子樹的深度 */ hr=PostTreeDepth(bt->RChild); /* 求右子樹的深度 */ max=hl>hr?hl:hr; /* 得到左、右子樹深度較大者*/ return(max+1); /* 返回樹的深度 */ } else return(0); /* 如果是空樹,則返回0 */ } int Hmax=0; // 先序遍歷求二叉樹bt高度的遞迴演算法,h為bt指向結點所在層次,初值為1 //depth為當前求得的最大層次,為全域性變數,呼叫前初值為0 void PreTreeDepth(BiTree bt, int h) { if(bt==NULL) return ; if(bt->LChild==NULL&&bt->RChild==NULL) { Hmax = Hmax>h ? Hmax:h; } PreTreeDepth(bt->LChild, h+1); /* 遍歷左子樹 */ PreTreeDepth(bt->RChild, h+1); /* 遍歷右子樹 */ } int main() { BiTree tree; CreateBiTree(&tree); printf("PreOrder:\n"); PreOrder(tree); printf("\nInOrder:\n"); InOrder(tree); printf("\nPostOrder:\n"); PostOrder(tree); printf("\nPreOrder1:\n"); PreOrder1(tree); printf("\nPreOrder2:\n"); PreOrder2(tree); printf("葉子數:%d\n",leaf(tree)); printf("後序遍歷求二叉樹bt高度:%d\n",PostTreeDepth(tree)); Hmax=0; PreTreeDepth(tree,1); printf("\nPreTreeDepth: % d\n",Hmax); return 0; } /*ABDE..F...CGI...HJ..K.L..*/