• PAT 1043【BST与二叉树】


    考察:
    1.二叉树的建树
    2.前序遍历,后序遍历
    3.BST的特性


    这题的思路:
    告诉你数组是先序遍历的,so 根已经知道了(数组首位元素),那么按照BST,建一下树(要两次,另外一次是镜像的);
    跑一跑先序遍历,对一对是不是呀?
    然后是的话就输出后序遍历的方式。

    THAT'S ALL;

    #include <bits/stdc++.h>
    using namespace std;
    typedef long long LL;
    
    const int N=1e3+10;
    
    struct BST{
    	BST* Left;
    	BST* Right;
    	int w;
    };
    
    BST* Insert1(BST* p,int w)
    {
    	if(p==NULL)
    	{
    		p=(BST*)malloc(sizeof(BST));
    		p->w=w;
    		p->Left=NULL;
    		p->Right=NULL;
    		return p;
    	}
    	if(w>=p->w)
    		p->Right=Insert1(p->Right,w);
    	else
    		p->Left=Insert1(p->Left,w);
    	return p;
    }
    
    BST* Insert2(BST* p,int w)
    {
    	if(p==NULL)
    	{
    		p=(BST*)malloc(sizeof(BST));
    		p->w=w;
    		p->Left=NULL;
    		p->Right=NULL;
    		return p;
    	}
    	if(w<p->w)
    		p->Right=Insert2(p->Right,w);
    	else
    		p->Left=Insert2(p->Left,w);
    	return p;
    }
    
    vector<int>xs;
    void Preorder(BST* p)
    {
    	if(p==NULL) return;
    	xs.push_back(p->w);
    	Preorder(p->Left);
    	Preorder(p->Right);
    }
    
    
    void Postorder(BST* p)
    {
    	if(p==NULL) return;
    	Postorder(p->Left);
    	Postorder(p->Right);
    	xs.push_back(p->w);
    }
    
    int main()
    {
    	int n;
    	int a[N];
    	scanf("%d",&n);
    	for(int i=1;i<=n;i++)
    		scanf("%d",&a[i]);
    	bool f1=true,f2=true;
    	BST* root;
    	root=(BST*)malloc(sizeof(BST));
    	root->w=a[1];
    	root->Left=NULL;
    	root->Right=NULL;
    	for(int i=2;i<=n;i++)
    		Insert1(root,a[i]);
    	xs.clear();
    	Preorder(root);
    	for(int i=0;i<n;i++)
    		if(a[i+1]!=xs[i])
    		{
    			f1=false;
    			break;
    		}
    	if(!f1)
    	{
    		root=(BST*)malloc(sizeof(BST));
    		root->w=a[1];
    		root->Left=NULL;
    		root->Right=NULL;
    		for(int i=2;i<=n;i++)
    			Insert2(root,a[i]);
    		xs.clear();
    		Preorder(root);
    		for(int i=0;i<n;i++)
    			if(a[i+1]!=xs[i])
    			{
    				f2=false;
    				break;
    			}
    	}
    	if(!f1&&!f2)
    	{
    		puts("NO");
    		return 0;
    	}
    	puts("YES");
    	xs.clear();
    	Postorder(root);
    	for(int i=0;i<n;i++)
    	{
    		if(i) printf(" ");
    		printf("%d",xs[i]);
    	}
    	return 0;
    }
    
    
    
    
    


  • 相关阅读:
    检测对象类型的两种方式,constructor属性和instanceof
    Javascript中的事件
    工厂模式、寄生构造函数模式、稳妥构造函数模式比较
    ECMAScript中的原型继承
    Javascript中new的作用
    js组合继承
    【原型模式】--重写原型对象prototype的影响
    动态原型模式
    js类型检测
    Javascript中的继承与复用
  • 原文地址:https://www.cnblogs.com/keyboarder-zsq/p/6777362.html
Copyright © 2020-2023  润新知