二叉排序树建立的输入问题

二叉树建立的输入问题,对于空闲叶子节点,需要用特殊字符标记。二叉排序树建立的输入问题与之相反,只需要将要输入的数据一股脑的输入即可,不需要对特殊字符进行判别,需要对新输入的数据大小进行判别,却也造成了返回值的问题。解决代码如下,亲测有效。

#include<iostream>
using namespace std;

struct node
{
	int data;
	node *left;
	node *right;
	node(){left=NULL;right=NULL;};
};

node *insert(node *root,int a)
{
	if(root==NULL)
	{
		root=new node;
		root->data=a;
		return root;
	}
	else if(a<root->data)
	root->left=insert(root->left,a);
	else if(a>root->data)
	root->right=insert(root->right,a);
	
	return root; 
}

void preorder(node *root)
{
	if(root)
	{
		cout<<root->data<<" ";
		preorder(root->left);
		preorder(root->right); 
	}
}

void inorder(node *root)
{
	if(root)
	{
		inorder(root->left);
		cout<<root->data<<" ";
		inorder(root->right); 
	}
}

void postorder(node *root)
{
	if(root)
	{
		postorder(root->left);
		postorder(root->right);
		cout<<root->data<<" ";
	}
}

int main()
{
	node *root;
	root=NULL;
	int n;
	cin>>n;
	int a;
	for(int i=0;i<n;i++)
	{
		cin>>a;
		root=insert(root,a);
	}
	cout<<endl;
	cout<<"先序遍历"<<endl; 
	preorder(root);
	cout<<endl;
	cout<<"中序遍历"<<endl;
	inorder(root);
	cout<<endl;
	cout<<"后序遍历"<<endl;
	postorder(root);
	cout<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wudongming_000/article/details/82857966