PAT (Advanced Level) Practice 1043 Is It a Binary Search Tree

利用本题, 复习二叉搜索树的创建(插入),先序遍历和后序遍历,以及掌握BST的特性

以下来自《算法笔记》对二叉查找树的介绍

二叉查找树(Binary Search Tree, BST)是一种特殊的二叉树,又称排序二叉树、二叉搜索树、二叉排序树。二叉查找树的递归定义如下:
1.要么二叉查找树是一棵空树
2.要么二叉查找树由根节点、左子树、右子树组成,其中左子树和右子树都是二叉树查找树,且左子树上所有结点的数据域均小于或等于根节点的数据域,右子树上所有结点的数据域均大于根节点的数据域。

从二叉查找树的定义中可以知道,二叉查找树实际上是一棵数据域有序的二叉树。
二叉查找树一个实用的性质:对二叉查找树进行中序遍历,遍历的结果是有序的。

注意:定义根结点时要将其设为空节点(一开始是没有元素的);在新建结点时要注意将其左右子结点地址设为NULL

题目

#include <cstdio>
#include <cstring>
const int maxn=1e3+1;
int n, a[maxn], b[maxn], c[maxn];
int cnt=0;
struct node{
	int data;
	node* lchild;
	node* rchild;
}; 

node* newnode(int x){
	node* temp=new node;
	temp->data=x;
	temp->lchild=NULL;
	temp->rchild=NULL;
	return temp;
}

void insert(node* &root, int x){  //插入 
	if(root==NULL){
		root=newnode(x);
		return;
	}
 	
	if(root->data>x)
	    insert(root->lchild, x);
	else
	    insert(root->rchild, x);	
}

node* Create(){  //创建 
    node* root=NULL;  //pay attention please!!!;
	for(int i=0; i<n; i++)
	    insert(root, a[i]);
	
	return root;    	
} 

void traversal1(node* root){
	if(cnt==n)
	    return;
	if(root==NULL)
	    return;
	    
	b[cnt++]=root->data;
	traversal1(root->lchild);
	traversal1(root->rchild);
}

void traversal2(node* root){
	if(cnt==n)
	    return;
	if(root==NULL)
	    return;
  
	b[cnt++]=root->data;
	traversal2(root->rchild);
	traversal2(root->lchild);	
}

void postorder1(node* root){  //后序遍历——先左后右,最后根 
	if(root==NULL)
		return;
	    
	postorder1(root->lchild);
	postorder1(root->rchild); 
	c[cnt++]=root->data;
}

void postorder2(node* root){  //后序遍历——先左后右,最后根 
	if(root==NULL)
		return;
	    
	postorder2(root->rchild);
	postorder2(root->lchild); 
    c[cnt++]=root->data;
}

int main()
{
	scanf("%d", &n);
	for(int i=0; i<n; i++)
	    scanf("%d", &a[i]);
	    
	node* root=Create();
	bool f1=true, f2=true;
	cnt=0;
	traversal1(root);
	for(int i=0; i<n; i++){
		if(a[i]!=b[i]){
			f1=false;
			break;
		}
	}
	 
	cnt=0;   
	traversal2(root);
    for(int i=0; i<n; i++){
    	if(a[i]!=b[i]){
    		f2=false;
    		break;
		}
	}
     
	cnt=0;   
	if(f1 || f2){
		printf("YES\n");
		if(f1)
		    postorder1(root);
		if(f2)
		    postorder2(root);
		
		for(int i=0; i<n; i++){
			printf("%d", c[i]);
			if(i!=n-1)
			    printf(" ");
			else
			    printf("\n");
		}
	} else
	    printf("NO\n");
	    
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值