二叉排序树创建(递归)
#include<stdio.h>#include<stdlib.h>/*递归前中后遍历*/typedefstructnode{intdata;structnode*left;structnode*right;}BTnode;BTnode*CreateTree(BTnode*root,intx){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);//递归调用左elseif(root->data<x)root->right=CreateTree(root->right,x);//递归调用右}returnroot;}voidForder(BTnode*root){if(root){printf("%d",root->data);printf("\n");Forder(root->left);Forder(root->right);}}voidInorder(BTnode*root){if(root){Inorder(root->left);printf("%3d",root->data);printf("\n");Inorder(root->right);}}voidPorder(BTnode*root){if(root){Porder(root->left);Porder(root->right);printf("%6d",root->data);printf("\n");}}intmain(void){BTnode*head=NULL;intx;intn;inti;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);}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。