How to rebuild BST using {tra, in, post}

We know the preliminary, ordinal and post-orders. What algorithm will restore BST?

+3
source share
4 answers

Since this is a BST, in-orderyou can sort from pre-orderor post-order<1>. In fact, it only requires pre-orderor post-order....

<1> if you know the comparison function


From pre-orderand in-orderto build a binary tree

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 for this is:

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

Similar for post-orderand in-order.

+11

+ +. BST, , , , inorder.

, , @brainydexter, :

struct node* buildTree(char in[],char pre[], int inStrt, int inEnd,int preIndex){

    // start index > end index..base condition return NULL.
    if(inStrt > inEnd)
        return NULL;

    // build the current node with the data at pre[preIndex].
    struct node *tNode = newNode(pre[preIndex]);

    // if all nodes are constructed return. 
    if(inStrt == inEnd)
        return tNode;

    // Else find the index of this node in Inorder traversal
    int inIndex = search(in, inStrt, inEnd, tNode->data);

    // Using index in Inorder traversal, construct left and right subtress
    tNode->left = buildTree(in, pre, inStrt, inIndex-1,preIndex+1);
    tNode->right = buildTree(in, pre, inIndex+1, inEnd,preIndex+inIndex+1);

    return tNode;
}
0

Ruby

def rebuild(preorder, inorder)
  root = preorder.first
  root_inorder = inorder.index root
  return root unless root_inorder
  root.left = rebuild(preorder[1, root_inorder], inorder[0...root_inorder])
  root.right = rebuild(preorder[root_inorder+1..-1], inorder[root_inorder+1..-1])
  root
end

class Node
  attr_reader :val
  attr_accessor :left, :right

  def initialize(val)
    @val = val
  end

  def ==(node)
    node.val == val
  end

  def inspect
    "val: #{val}, left: #{left && left.val || "-"}, right: #{right && right.val || "-"}"
  end
end

inorder = [4, 7, 2, 5, 1, 3, 8, 6, 9].map{|v| Node.new v }
preorder = [1, 2, 4, 7, 5, 3, 6, 8, 9].map{|v| Node.new v }

tree = rebuild(preorder, inorder)
tree
# val: 1, left: 2, right: 3
tree.left
# val: 2, left: 4, right: 5
tree.left.left
# val: 4, left: -, right: 7
0

All Articles