zoukankan      html  css  js  c++  java
  • A1043 Is It a Binary Search Tree [bst]

    在这里插入图片描述
    题目思路:先建树,先序遍历一遍和输入的比较判断是yes还是no,然后注意镜像树先序就是先遍历右边的 后序也先遍历右边的

    
    #include<iostream>
    #include<vector>
    #include<queue>
    #include<stack>
    #include<string>
    #include<math.h>
    #include<algorithm>
    using namespace std;
    struct node {
    	int data;
    	node* left, * right;
    };
    void insert(node* &root, int data)
    {
    	if (root == NULL)
    	{
    		root = new node;
    		root->data = data;
    		root->left = root->right = NULL;
    		return;
    	}
    	if (data < root->data) insert(root->left, data);
    	else insert(root->right, data);
    }
    void preorder1(node* root, vector<int>& v1)
    {
    	if (root == NULL) return;
    	v1.push_back(root->data);
    	preorder1(root->left, v1);
    	preorder1(root->right, v1);
    }
    void preorder2(node* root, vector<int>& v1)
    {
    	if (root == NULL) return;
    	v1.push_back(root->data);
    	preorder2(root->right, v1);
    	preorder2(root->left, v1);
    }
    void postorder1(node* root, vector<int>& v1)
    {
    	if (root == NULL) return;
    	postorder1(root->left, v1);
    	postorder1(root->right, v1);
    	v1.push_back(root->data);
    }
    void postorder2(node* root, vector<int>& v1)
    {
    	if (root == NULL) return;
    	postorder2(root->right, v1);
    	postorder2(root->left, v1);
    	v1.push_back(root->data);
    }
    vector<int>v0,v1, v2, v3, v4;
    int main()
    {
    	int n, data;
    	cin >> n;
    	node* root = NULL;
    	for (int i = 0; i < n; i++)
    	{
    		cin >> data;
    		v0.push_back(data);
    		insert(root, data);
    	}
    	preorder1(root, v1);
    	preorder2(root, v2);
    	postorder1(root, v3);
    	postorder2(root, v4);
    	if (v0 == v1)
    	{
    		cout << "YES" << endl;
    		for (int i = 0; i < v3.size(); i++)
    		{
    			cout << v3[i];
    			if (i < v3.size() - 1)
    				cout << " ";
    		}
    	}
    	else if (v0 == v2)
    	{
    		cout << "YES" << endl;
    		for (int i = 0; i < v4.size(); i++)
    		{
    			cout << v4[i];
    			if (i < v4.size() - 1)
    				cout << " ";
    		}
    	}
    	else
    	{
    		cout << "NO" << endl;
    	}
    }
    
  • 相关阅读:
    MySQL中的while循环和repeat循环的区别
    Python 基础语法_Python脚本文件结构
    Python 基础语法_Python脚本文件结构
    MySQL存储过程和函数的区别
    第四章 语句和声明
    haproxy 4层和7层负载
    献血是件很赞的事——北漂18年(26)
    JavaScript字符串数值比较问题
    MySQL查看所有可用的字符集
    MySQL获取表格信息
  • 原文地址:https://www.cnblogs.com/Hsiung123/p/13812008.html
Copyright © 2011-2022 走看看