华农专业课拯救计划:验证二叉搜索树序列

1.问题整体复制,让你快速的找到我

【问题描述】输入一个整数数组,判断该数组是不是某二叉查找树(折半查找树)后序遍历的结果。如果是返回true,否则返回false。
【输入形式】输入任意长度的数组,数字之间空格分开
【输出形式】true 或者 false
【样例输入】输入5 7 6 9 11 10 8
【样例输出】true
【样例说明】由于这一整数序列是如下树的后序遍历结果:

          8
       /      \
      6      10
    /   \     /   \
   5   7   9  11

因此返回true。

【评分标准】暴力求解法不得分。

【提示】后序遍历的最后一个结点一定是根结点,那么前面的数据就可以划分为比根小的、比根大的。依此类推下去。

2.不废话,先复制代码

#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct node
{
    int data;
    struct node* LChild;
    struct node* RChild;
}SortTreeNode, * SortTree;

SortTree root;
int a[20];
int res[20];
int cnt = 0;

void Insert(int node)
{
    SortTreeNode* ptr = root;
    SortTreeNode* pre = NULL;
    while (ptr != NULL)
    {
        if (a[node] < ptr->data)
        {
            pre = ptr;
            ptr = ptr->LChild;
        }
        else
        {
            pre = ptr;
            ptr = ptr->RChild;
        }
    }
    SortTreeNode* temp = (SortTree)malloc(sizeof(SortTreeNode));
    temp->data = a[node];
    temp->LChild = NULL;
    temp->RChild = NULL;
    if (temp->data < pre->data)
    {
        pre->LChild = temp;
    }
    else
    {
        pre->RChild = temp;
    }
}

void Creat(int limit)
{
    int i = limit - 1;
    root = (SortTree)malloc(sizeof(SortTreeNode));
    root->data = a[i];
    root->LChild = NULL;
    root->RChild = NULL;
    i--;
    while (i >= 0)
    {
        Insert(i);
        i--;
    }
}

void PostOrder(SortTreeNode* r)
{
    if (r != NULL)
    {
        PostOrder(r->LChild);
        PostOrder(r->RChild);
        res[cnt++] = r->data;
    }
    return;
}

int main()
{
    int i = 0;
    while (cin >> a[i])
    {
        i++;
    }
    Creat(i); //i取不到
    PostOrder(root);
    for (i = 0; i < cnt; i++)
    {
        if (res[i] != a[i])
        {
            break;
        }
    }
    if (i == cnt) cout << "true";
    else cout << "false";
}

3.简单聊聊思想

这道题的主要思想为构建一个二叉搜索树,带排序节点的,就是用一个12345等为下标的数组构建二叉搜索树,然后把后序遍历对号入座,再进行后序遍历,看看是否和原来的后序遍历不一样,不一样则输出false

  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值