zoukankan      html  css  js  c++  java
  • L2-004 这是二叉搜索树吗?

    L2-004 这是二叉搜索树吗?(25分)

    题意

    给你一个搜索二叉树的前序遍历(可能是错的),让你检测它或者它的镜像是不是真的搜索二叉树,是的话输出它的后续遍历

    思路

    直接模拟一遍,比较考验基本功。

    #include <cstdio>
    #include <iostream>
    #include <algorithm>
    #include <cmath>
    #include <cstdlib>
    #include <cstring>
    #include <string>
    #include <map>
    #include <stack>
    #include <queue>
    #include <vector>
    #include <bitset>
    #include <set>
    #include <utility>
    #define inf 0x3f3f3f3f
    #define INF 0x3f3f3f3f3f3f3f3f
    #define mem(a, b) memset(a, b, sizeof(a))
    #define pb push_back
    #define ll long long
    using namespace std;
    const double PI = acos(-1.0);
    const int N = 2e5 + 10;
    const int mod = 1e9 + 7;
    /////////////////////////////////////////
    typedef struct node
    {
    	struct node *l, *r;
    	int data;
    } tr;
    vector<int> a;
    vector<int> pre;
    vector<int> post;
    tr *insert_(tr *rt, int cur)
    {
    	if (rt == NULL)
    	{
    		rt = new tr;
    		rt->data = cur;
    		rt->l = rt->r = NULL;
    	}
    	else
    	{
    		if (rt->data > cur)
    		{
    			rt->l = insert_(rt->l, cur);
    		}
    		else
    		{
    			rt->r = insert_(rt->r, cur);
    		}
    	}
    	return rt;
    }
    void pre_(tr *rt)
    {
    	if (rt != NULL)
    	{
    		pre.pb(rt->data);
    		pre_(rt->l);
    		pre_(rt->r);
    	}
    	return;
    }
    void post_(tr *rt)
    {
    	if (rt != NULL)
    	{
    		post_(rt->l);
    		post_(rt->r);
    		post.pb(rt->data);
    	}
    	return;
    }
    tr *aaaa(tr *rt)
    {
    	if (rt == NULL)
    	{
    		return NULL;
    	}
    	rt->l = aaaa(rt->l);
    	rt->r = aaaa(rt->r);
    	swap(rt->l, rt->r);
    	return rt;
    }
    int main()
    {
    	int n;
    	cin >> n;
    	tr *rt = NULL;
    	for (int i = 1; i <= n; i++)
    	{
    		int cur;
    		cin >> cur;
    		a.pb(cur);
    		rt = insert_(rt, cur);
    	}
    	pre_(rt);
    	int ok = 1;
    	for (int i = 0; i < n; i++)
    	{
    		if (a[i] != pre[i])
    		{
    			ok = 0;
    			break;
    		}
    	}
    	if (ok)
    	{
    		post_(rt);
    		cout << "YES" << endl;
    		for (int i = 0; i < n-1; i++)
    		{
    			cout << post[i] << " ";
    		}
    		cout<<post[n-1];
    		return 0;
    	}
    	pre.clear();
    	rt = aaaa(rt);
    	pre_(rt);
    	for (int i = 0; i < n; i++)
    	{
    		if (a[i] != pre[i])
    		{
    			ok = 0;
    			cout << "NO" << endl;
    			return 0;
    		}
    	}
    	post_(rt);
    	cout << "YES" << endl;
    	for (int i = 0; i < n-1; i++)
    	{
    		cout << post[i] << " ";
    	}
    	cout<<post[n-1];
    	return 0;
    }
    
  • 相关阅读:
    初级模拟玩骰子猜大小游戏
    会员号的百位数字等于产生的随机数即为幸运会员
    课外作业1:将一个double类型的小数,按照四舍五入保留两位小数
    git idea tag push
    java进程资源监控
    websocket
    kafka win10搭建 单机版
    kafka细节知识---mark
    Springboot 1.5.7整合Kafka-client
    redis安装 centos
  • 原文地址:https://www.cnblogs.com/Aracne/p/13767583.html
Copyright © 2011-2022 走看看