algorithm - 给定后序遍历如何构建BST

标签 algorithm recursion binary-tree binary-search-tree

我知道有一些方法可以从预序遍历(作为数组)构建树。更常见的问题是在给定中序和先序遍历的情况下构造它。在这种情况下,中序遍历虽然是多余的,但绝对让事情变得简单。谁能告诉我如何进行后序遍历?需要迭代和递归解决方案。

我尝试使用堆栈迭代地完成它,但根本无法正确理解逻辑,所以得到了一棵可怕的凌乱树。递归也是如此。

最佳答案

如果您有一个来自 BST 后序遍历的数组,您知道根是数组的最后一个元素。根的左 child 占据数组的第一部分,并且由小于根的条目组成。然后是右 child ,由大于根的元素组成。 (两个 child 都可能是空的)。

________________________________
|             |              |R|
--------------------------------
 left child     right child   root

所以主要的问题是找到左 child 结束和右 child 开始的点。

这两个 child 也是从他们的后序遍历中获得的,所以构造他们也是以同样的方式递归完成的。

BST fromPostOrder(value[] nodes) {
    // No nodes, no tree
    if (nodes == null) return null;
    return recursiveFromPostOrder(nodes, 0,  nodes.length - 1);
}

// Construct a BST from a segment of the nodes array
// That segment is assumed to be the post-order traversal of some subtree
private BST recursiveFromPostOrder(value[] nodes, 
                                   int leftIndex, int rightIndex) {
    // Empty segment -> empty tree
    if (rightIndex < leftIndex) return null;
    // single node -> single element tree
    if (rightIndex == leftIndex) return new BST(nodes[leftIndex]);

    // It's a post-order traversal, so the root of the tree 
    // is in the last position
    value rootval = nodes[rightIndex];

    // Construct the root node, the left and right subtrees are then 
    // constructed in recursive calls, after finding their extent
    BST root = new BST(rootval);

    // It's supposed to be the post-order traversal of a BST, so
    // * left child comes first
    // * all values in the left child are smaller than the root value
    // * all values in the right child are larger than the root value
    // Hence we find the last index in the range [leftIndex .. rightIndex-1]
    // that holds a value smaller than rootval
    int leftLast = findLastSmaller(nodes, leftIndex, rightIndex-1, rootval);

    // The left child occupies the segment [leftIndex .. leftLast]
    // (may be empty) and that segment is the post-order traversal of it
    root.left = recursiveFromPostOrder(nodes, leftIndex, leftLast);

    // The right child occupies the segment [leftLast+1 .. rightIndex-1]
    // (may be empty) and that segment is the post-order traversal of it
    root.right = recursiveFromPostOrder(nodes, leftLast + 1, rightIndex-1);

    // Both children constructed and linked to the root, done.
    return root;
}

// find the last index of a value smaller than cut in a segment of the array
// using binary search
// supposes that the segment contains the concatenation of the post-order
// traversals of the left and right subtrees of a node with value cut,
// in particular, that the first (possibly empty) part of the segment contains
// only values < cut, and the second (possibly empty) part only values > cut
private int findLastSmaller(value[] nodes, int first, int last, value cut) {

    // If the segment is empty, or the first value is larger than cut,
    // by the assumptions, there is no value smaller than cut in the segment,
    // return the position one before the start of the segment
    if (last < first || nodes[first] > cut) return first - 1;

    int low = first, high = last, mid;

    // binary search for the last index of a value < cut
    // invariants: nodes[low] < cut 
    //             (since cut is the root value and a BST has no dupes)
    // and nodes[high] > cut, or (nodes[high] < cut < nodes[high+1]), or
    // nodes[high] < cut and high == last, the latter two cases mean that
    // high is the last index in the segment holding a value < cut
    while (low < high && nodes[high] > cut) {

        // check the middle of the segment
        // In the case high == low+1 and nodes[low] < cut < nodes[high]
        // we'd make no progress if we chose mid = (low+high)/2, since that
        // would then be mid = low, so we round the index up instead of down
        mid = low + (high-low+1)/2;

        // The choice of mid guarantees low < mid <= high, so whichever
        // case applies, we will either set low to a strictly greater index
        // or high to a strictly smaller one, hence we won't become stuck.
        if (nodes[mid] > cut) {
            // The last index of a value < cut is in the first half
            // of the range under consideration, so reduce the upper
            // limit of that. Since we excluded mid as a possible
            // last index, the upper limit becomes mid-1
            high = mid-1;
        } else {
            // nodes[mid] < cut, so the last index with a value < cut is
            // in the range [mid .. high]
            low = mid;
        }
    }
    // now either low == high or nodes[high] < cut and high is the result
    // in either case by the loop invariants
    return high;
}

关于algorithm - 给定后序遍历如何构建BST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13167536/

相关文章:

c++ - 在 C++ 中将字符串插入 AVL 树?

algorithm - 在时间范围列表中查找(数量)重叠

algorithm - 三种情况下的大 O 符号复杂度

python - 深度列表计数 - 列表中的列表计数

c++ - 删除有两个 child 的目标

tree - 关于二叉树旋转

algorithm - 贪心算法实现,Haskell

algorithm - Facebook 图谱搜索 : Information Retrieval Algorithm

c# - 手动终止递归

java - 二项式系数。递归树。如何避免多次计算相同的值