zoukankan      html  css  js  c++  java
  • 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;
    }
    
    
    
    
    


  • 相关阅读:
    ASP.NET缓存全解析(系列)
    updateprogress用法技巧
    text与img对齐
    9款Firefox插件提高设计开发效率
    ASP.NET页面实时进行GZIP压缩优化
    如何收缩和删除SQL日志文件
    闲扯加班
    与大家分享一点游戏管理晋升的心得(完整版)
    FDS (Flex Data Services)
    和我老婆去旅游
  • 原文地址:https://www.cnblogs.com/keyboarder-zsq/p/6777362.html
Copyright © 2011-2022 走看看