搜索二叉树的建立及遍历--C语言描述

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
	int date;
	struct node * left, * right;
}BTnode;

//创建一个二叉树
BTnode * CreateBTtree(int A[], int n)
{
	BTnode *root, *c, *pa, *p;
	root = (BTnode*)malloc(sizeof(BTnode));
	root->date = A[0];
	root->left = root->right = NULL;
	for (int i = 1; i < n; i++)
	{
		p= (BTnode*)malloc(sizeof(BTnode));
		p->date = A[i];
		p->left = p->right = NULL;
		c = root;
		while (c!=NULL)
		{
			pa = c;
			if (c->date > p->date)
				c = c->left;
			else
				c = c->right;
		}
		if (pa->date > p->date)
			pa->left = p;
		else
			pa->right = p;
	}
	return root;
}

//前序遍历二叉树(先访问根节点,再访问左子树,最后访问右子树)
void FOrder(BTnode*root)
{
	if (root)
	{
		printf("%d ", root->date);
		FOrder(root->left);
		FOrder(root->right);
	}
}

//中序遍历(先访问左子树,再访问根节点,最后访问右子树)
void INorder(BTnode*root)
{
	if (root)
	{
		INorder(root->left);
		printf("%d ", root->date);
		INorder(root->right);
	}
}

int main(void)
{
	int A[9] = {7,5,3,4,9,6,8,1,2 };
	BTnode * root;
	root = CreateBTtree(A, 9);
	FOrder(root);
	printf("\n");
	INorder(root);
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值