首页 > 编程语言 > 详细

二叉排序树创建(递归)

时间:2018-08-09 18:21:53      阅读:101      评论:0      收藏:0      [点我收藏+]
#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); }


二叉排序树创建(递归)

原文:http://blog.51cto.com/13645380/2156899

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!