• 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;
    }
    
  • 相关阅读:
    课上作业
    大道至简第四章读后感
    课上作业
    读大道至简第三章感想
    关于外部引用JS,中文乱码的问题
    HTML5 之Canvas绘制太阳系
    HTML5 之Canvas 绘制时钟 Demo
    JQuery仿淘宝商家后台管理 之 管理添加分类
    分页存储过程的几种写法
    Javascript-do_while....
  • 原文地址:https://www.cnblogs.com/Aracne/p/13767583.html
Copyright © 2020-2023  润新知