搜索二叉树的建立及遍历

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

猜你喜欢

转载自blog.csdn.net/qq_42386328/article/details/83033627