您好,登錄后才能下訂單哦!
#include<stdio.h> #include<stdlib.h> typedef struct BinaryTreeNode { int data; struct BinaryTreeNode *Left; struct BinaryTreeNode *Right; }Node; //創建二叉樹,順序依次為中間節點->左子樹->右子樹 Node* createBinaryTree() { Node *p; int ch; printf("輸入data"); scanf("%d",&ch); if(ch == 0) //如果到了葉子節點,接下來的左、右子樹分別賦值為0 { p = NULL; } else { p = (Node*)malloc(sizeof(Node)); p->data = ch; p->Left = createBinaryTree(); //遞歸創建左子樹 p->Right = createBinaryTree(); //遞歸創建右子樹 } 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); } } //二叉樹節點總數目 int Nodenum(Node* root) { if(root == NULL) { return 0; } else { return 1+Nodenum(root->Left)+Nodenum(root->Right); } } //二叉樹葉子節點數 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; }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。