您好,登錄后才能下訂單哦!
#include<stdio.h> #include<stdlib.h> typedef struct BinaryTreeNode { int data; struct BinaryTreeNode *Left; struct BinaryTreeNode *Right; }Node; //創(chuàng)建二叉樹,順序依次為中間節(jié)點(diǎn)->左子樹->右子樹 Node* createBinaryTree() { Node *p; int ch; printf("輸入data"); scanf("%d",&ch); if(ch == 0) //如果到了葉子節(jié)點(diǎn),接下來(lái)的左、右子樹分別賦值為0 { p = NULL; } else { p = (Node*)malloc(sizeof(Node)); p->data = ch; p->Left = createBinaryTree(); //遞歸創(chuàng)建左子樹 p->Right = createBinaryTree(); //遞歸創(chuàng)建右子樹 } return p; } //先序遍歷 void preOrderTraverse(Node* root) { if( root ) { printf("%d",root->data); preOrderTraverse(root->Left); preOrderTraverse(root->Right); } } //中序遍歷 void inOrderTraverse(Node* root) { if( root ) { inOrderTraverse(root->Left); printf("%d",root->data); inOrderTraverse(root->Right); } } //后序遍歷 void lastOrderTraverse(Node* root) { if( root ) { lastOrderTraverse(root->Left); lastOrderTraverse(root->Right); printf("%d",root->data); } } //二叉樹節(jié)點(diǎn)總數(shù)目 int Nodenum(Node* root) { if(root == NULL) { return 0; } else { return 1+Nodenum(root->Left)+Nodenum(root->Right); } } //二叉樹葉子節(jié)點(diǎn)數(shù) int Leafnum(Node* root) { if(!root) { return 0; } else if( (root->Left == NULL) && (root->Right == NULL) ) { return 1; } else { return (Leafnum(root->Left) + Leafnum(root->Right)) ; } } int main() { int i; Node *root = NULL; root = createBinaryTree(); printf("二叉樹建立成功"); printf("\n"); preOrderTraverse(root); printf("\n"); inOrderTraverse(root); printf("\n"); lastOrderTraverse(root); printf("\n"); i = Leafnum(root); printf("%d",i); printf("\n"); i = Nodenum(root); printf("%d",i); return 0; }
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。