您好,登錄后才能下訂單哦!
#include<stdio.h> #include<stdlib.h> /* 遞歸前中后遍歷 */ typedef struct node { int data; struct node*left; struct node*right; }BTnode; BTnode* CreateTree(BTnode* root,int x) { if(!root) //如果root結點為空,創建葉子結點 { root = (BTnode*)malloc(sizeof(BTnode)); root->data = x; root->left=root->right=NULL; }else { if(root->data>x) root->left = CreateTree(root->left,x); //遞歸調用左 else if(root->data<x) root->right = CreateTree(root->right,x);//遞歸調用右 } return root; } void Forder(BTnode*root) { if(root) { printf("%d",root->data); printf("\n"); Forder(root->left); Forder(root->right); } } void Inorder(BTnode*root) { if(root) { Inorder(root->left); printf("%3d",root->data); printf("\n"); Inorder(root->right); } } void Porder(BTnode*root) { if(root) { Porder(root->left); Porder(root->right); printf("%6d",root->data); printf("\n"); } } int main(void) { BTnode * head = NULL; int x; int n; int i; printf("請輸入n="); scanf("%d",&n); printf("請輸入二叉樹的結點data\n"); for(i=0;i<n;i++) { scanf("%d",&x); head = CreateTree(head,x); } printf("..................\n"); Forder(head); printf("..................\n"); Inorder(head); printf("..................\n"); Porder(head); }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。