Binary tree from Preorder and inorder traversal

后端 未结 3 1876
小蘑菇
小蘑菇 2021-01-07 05:37

How can I get the tree form these pre/in order traversal:

Pre: A,B,D,E,C,F,G,H in:E,D,B,A,G,F,H,C

EDITED: MY Answer

       A         


        
3条回答
  •  旧巷少年郎
    2021-01-07 06:12

    EDIT: Correction,

    You don't have the correct answer, FGH is to the left of C.

    To verify just run the two algorithms against it:

    PreOrder(node)
      if node is null return
      Print(node)
      PreOrder(node.left)
      PreOrder(node.Right)
    
    InOrder(node)
      if node is null return
      InOrder(node.left)
      Print(node)
      InOrder(node.Right)
    

    You know that A is the root because it starts the pre-order. Use the in-order to arrange nodes to the left and right of A. B is the second node (pre-order), and left of A (in-order), and so on.

    You know that F,G,H is left of C because of the in-order arrangement.

    Basically, use preorder to select the next node, and in-order to see whether it is left or right of the parent node.

    EDIT (18 Apr 2011):

    To show how mechanical the process is I offer this pseudo code:

    // Add method on binary tree class -- stock standard
    method Add(item, comparer)
      newNode = new Node(item)
      parent = null
    
      // Find suitable parent
      currentNode = root
      while currentNode is not null
        parent = currentNode
        if comparer(newNode.Key, currentNode.Key) < 0
          currentNode = currentNode.Left
        else 
          currentNode = currentNode.Right
    
      // Add new node to parent
      if parent is null
        root = newNode
      else if comparer(newNode.Value, parent.Value) < 0 
        parent.Left = newNode
      else 
        parent.Right = newNode
    

    The trick is to use the in-order sequence to determine whether a node is added to the left or right of its parent, for example:

    // Client code
    // Input arrays
    var preOrder = ["A","B","D","E","C","F","G","H"]
    var inOrder  = ["E","D","B","A","G","F","H","C"]
    // A collection associating the Key value with its position in the inOrder array
    var inOrderMap = GetInOrderMap(inOrder)
    
    // Build tree from pre-order and in-order sequences
    foreach (item in preOrder) 
      Add(item, fun (l, r) -> inOrderMap[l] - inOrderMap[r])
    

    I'm passing a lamba, but any equivalent method for passing a comparer should do.

提交回复
热议问题