已知二叉树的两种搜索序列,建立二叉树问题

对于先序搜索,二叉树结点和左节点的搜索是相继的。对于其他的搜索方式,父子节点或者兄弟节点之间的数据搜索不是相继的。

1.已知先序搜索和中序搜索,求后续搜索。

原题 洛谷  https://www.luogu.com.cn/problem/P1827

递归思想,中序搜索可以把二叉树分而治之

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

struct knot
{
    char name;
    knot *left;
    knot *right;
};
knot *build(char *, char *);
void lsearch(knot *root);
char fsearch[28];
char msearch[28];
int cur = 0;
int main()
{
    int num;

    cin >> msearch >> fsearch;
    num = strlen(msearch);
    knot *root = build(msearch, msearch + num - 1);
    lsearch(root);
    return 0;
}
//cur标记对于先序序列访问到了第几个元素
//[former,latter]是搜索的范围
knot *build(char *former, char *latter)
{
    knot *root = new knot;
    char temp = fsearch[cur];
    char *position = find(former, latter + 1, temp);
    root->name = fsearch[cur];
    cur++;
    if (former == latter)
    {
        root->right = nullptr;
        root->left = nullptr;
        return root;
    }
    if (position - 1 >= former)
        root->left = build(former, position - 1);
    else
        root->left = nullptr;
    if (position + 1 <= latter)
        root->right = build(position + 1, latter);
    else
        root->right = nullptr;
    return root;
}
//后序遍历
void lsearch(knot *root)
{
    if (root->left != nullptr)
        lsearch(root->left);
    if (root->right != nullptr)
        lsearch(root->right);
    cout << root->name;
    return;
}

有范围的查找,也可以判断这个二叉树有没有解

但是也可以不建树来解,这道题说白了就是一个切割字符串的问题。

2.如果已知二叉树的中序遍历和后序遍历,写出前序遍历,思路是一样的。

3.给定一个二叉树的前序遍历和后序遍历,二叉树往往不是唯一的,中序遍历也不唯一。

关键在于,唯一能导致树多种状态的是有一个孩子的节点

可以有孩子下面的子树当成整体的思想

 

posted @ 2021-04-01 21:45  Macondo's  阅读(100)  评论(0)    收藏  举报