標籤:lse std scanf roo return tree head nod scan
#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);}
二叉排序樹建立(遞迴)