如何BST使用{pre,在,后期}为了遍历结果重建 [英] how to rebuild BST using {pre,in,post}order traversals results

查看:142
本文介绍了如何BST使用{pre,在,后期}为了遍历结果重建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道pre-顺序,按顺序和后序遍历。什么算法将重建BST?

We know the pre-order, in-order and post-order traversals. What algorithm will reconstruct the BST?

推荐答案

由于它是BST,有序可以从 $ P排序$ P级后序< 1>。其实,无论是 pre级后序时,才需要......

Because it is BST, in-order can be sorted from pre-order or post-order <1>. Actually, either pre-order or post-order is needed only....

&LT; 1>如果您知道的比较函数是什么

<1> if you know what the comparison function is

pre级有序,构造一个二叉树

BT createBT(int* preOrder, int* inOrder, int len)
{
    int i;
    BT tree;
    if(len <= 0)
        return NULL;
    tree = new BTNode;
    t->data = *preOrder;
    for(i = 0; i < len; i++)
        if(*(inOrder + i) == *preOrder)
            break;
    tree->left = createBT(preOrder + 1, inOrder, i);
    tree->right = createBT(preOrder + i + 1, inOrder + i + 1, len - i - 1);
    return tree;
}

这样做的理由:

The rationale behind this:

在$ P $对 - 顺序,第一节点为根。发现在有序的根源。然后该树可以分为左,右。做到这一点递归。

In pre-order, the first node is the root. Find the root in the in-order. Then the tree can be divided into left and right. Do it recursively.

相似后序有序

这篇关于如何BST使用{pre,在,后期}为了遍历结果重建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆