---恢复内容开始---
输入n,然后n个树,建立二叉查找树。从小到大输出每个节点的左右子树,空输出#
///修改了根节点无用的情况
#include<cstdio>
#include<iostream>
using namespace std;
typedef struct node{
int data;
struct node *lchild,*rchild;
}NODE;
bool isempty=true;
void input(NODE *root,int value){
if(isempty)
{
root->data=value;
isempty=false;
}
if(value==root->data){
return;
}
else if(value>root->data){
if(root->rchild==NULL){
root->rchild=new NODE;
root->rchild->data=value;
root->rchild->lchild=NULL;
root->rchild->rchild=NULL;
}
else{
input(root->rchild,value);
}
}
else{
if(root->lchild==NULL){
root->lchild=new NODE;
root->lchild->data=value;
root->lchild->lchild=NULL;
root->lchild->rchild=NULL;
}
else{
input(root->lchild,value);
}
}
}
int n;
void preorder(NODE *root){
if(root==NULL)return;
preorder(root->lchild);
printf("%d(",root->data);
if(root->lchild==NULL){
printf("#");
}
else{
printf("%d",root->lchild->data);
}
if(root->rchild==NULL){
printf(", #)\n");
}
else{
printf(", %d)\n",root->rchild->data);
}
preorder(root->rchild);
}
int main(){
NODE *root=new NODE;
root->lchild=root->rchild=NULL;
int a;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&a);
input(root,a);
}
preorder(root);
return 0;
}

京公网安备 11010502036488号