Search code examples
binary-treeprefix

Construct binary tree from prefix order expression


How should we construct the binary tree of the following "prefix" order expression?

( - * / 8 + 5 1 4 + 3 - 5 / 18 6 )

Is there any rule to follow for drawing the tree?


Solution

  • Pseudocode is like this:

    function MakeBinaryTree(expr):
      element = next element in expr
      if element is a number:
        return a leaf node of that number
      else: // element is an operator
        left = MakeBinaryTree(expr)
        right = MakeBinaryTree(expr)
        return a binary tree with subtrees left and right and with operator element
    

    Here expr keeps an internal pointer pointing to where the next element is.