链式二叉搜索树的创建及遍历

二叉搜索树:左子女的值小于或等于根节点的值,右子女的值大于根节点的值。

设数据集合:data={5,4,6,3,2,1,7,9,8};

1、节点类型:

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

2、算法:

(1)创建根节点

	root=(BTP)malloc(sizeof(BTnode));
	root->left =root->right =NULL;
	root->data =D[0];

(2)遍历数据集合
1‘创建节点

		p=(BTP)malloc(sizeof(BTnode));
		p->left =p->right =NULL;
		p->data =D[i];
		cu=root;
2‘查找双亲
while(cu)
		{
			pa=cu;
			if(p->data <=cu->data )  cu=cu->left ;
			else cu=cu->right ;
		}

3’插入节点
	if(p->data <=pa->data )  pa->left =p;
		else
			pa->right =p;




(3)遍历二叉树(递归)

1‘前序遍历

void Foder(BTP root)
{
	if(root)
	{
		cout<<root->data <<endl;
		Foder(root->left );
		Foder(root->right );
	}
}

2’中序遍历

void Ioder(BTP root)
{
	if(root)
	{
		Ioder(root->left );
                cout<<root->data <<endl;
                Ioder(root->right );
         }
}

 
 3‘后序遍历 
 

void Poder(BTP root)
{
	if(root)
	{
		Poder(root->left );
		Poder(root->right ); 
                cout<<root->data <<endl;
         }
}
 
 


你可能感兴趣的:(递归,数据,遍历,二叉树)