1043 Is It a Binary Search Tree (25分)

Posted d-i-p

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1043 Is It a Binary Search Tree (25分)相关的知识,希望对你有一定的参考价值。

1. 题目

技术图片

2. 思路

  1. 如下图
    技术图片
    技术图片

发现规律,对于最左边来说,后面所有的集合都是先小后大或者先大后小,如果小大交错那么不符合

  1. 使用1中规律确定是否为镜像,结合二叉排序树的特点,用递归建立树
  2. 输出树的后序遍历

3. 注意点

  1. 发现规律比较困难
  2. 树的题目一般都要用递归

4. 代码

#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;

#define null NULL

struct node{
    int value;
    node* left;
    node* right;
    node(int _value){
        value = _value;
        left = null;
        right = null;
    }
};

int create(vector<int> nodes, int mode, node* &root){
    if(nodes.size() != 0){
        root = new node(nodes[0]);
    }else{
        return 1;
    }
    vector<int> left;
    vector<int> right;
    int i = 0;
    if(mode == 1){
        for(i=1;i<nodes.size();i++){
            if(nodes[i] > nodes[0]){
                break;
            }
            left.push_back(nodes[i]);
        }
        for(;i<nodes.size();i++){
            if(nodes[i] < nodes[0]){
                return 0;
            }
            right.push_back(nodes[i]);
        }
    }else{
        for(i=1;i<nodes.size();i++){
            if(nodes[i] < nodes[0]){
                break;
            }
            left.push_back(nodes[i]);
        }
        for(;i<nodes.size();i++){
            if(nodes[i] > nodes[0]){
                return 0;
            }
            right.push_back(nodes[i]);
        }
    }   
    int res1 = create(left, mode, root->left);
    int res2 = create(right, mode, root->right);
    return res1 & res2;
}

void post(node* root, int level){
    if(root == null){
        return ;
    }
    post(root->left, level+1);
    post(root->right, level+1);
    if(level == 0){
        printf("%d", root->value);
    }else{
        printf("%d ", root->value);
    }
}

int main() {
    int N;
    vector<int> nodes;
    scanf("%d", &N); 
    for(int i=0;i<N;i++){
        int v;
        scanf("%d", &v);
        nodes.push_back(v); 
    }
    int mode = 0; 
    for(int i=1;i<nodes.size();i++){
        if(nodes[i] < nodes[0]){
            mode = 1;
            break;
        }
        if(nodes[i] > nodes[0]){
            mode = 2;
            break;
        }
    }
    if(mode == 0){
        int i = 0;
        printf("YES
");
        for(i=0;i<nodes.size()-1;i++){
            printf("%d ", nodes[i]);
        }
        printf("%d", nodes[i]);
        return 0;
    }
    node* root;
    int res = create(nodes, mode, root);
    if(res == 0){
        printf("NO");
    }else{
        printf("YES
");
        post(root, 0);
    }
}

以上是关于1043 Is It a Binary Search Tree (25分)的主要内容,如果未能解决你的问题,请参考以下文章

1043 Is It a Binary Search Tree (25 分)

1043. Is It a Binary Search Tree (25)

1043. Is It a Binary Search Tree (25)

PAT1043 Is It a Binary Search Tree

PAT 1043 Is It a Binary Search Tree[二叉树][难]

1043 Is It a Binary Search Tree (25分)(树的插入)