温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

二叉排序树创建(递归)

发布时间:2020-04-08 21:38:14 来源:网络 阅读:1609 作者:闫宝通 栏目:编程语言
#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);

}


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI