1. 程式人生 > >二叉排序樹創建(遞歸)

二叉排序樹創建(遞歸)

size ret 二叉排序樹 遞歸 如果 nor std oid include

#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); }


二叉排序樹創建(遞歸)