Zeffia
Zeffia

Reputation: 37

Generating a binary tree using inorder and preorder traversal

I want to generate a binary tree using the following inorder/preorder traversal;

Inorder = WOLLONGONG

Preorder = GLOWOLNNGO

This is the tree I came up with:

       G
      /  \
     L    N
    / \  /  \
   O  O  O   G
  /  / \   
 W  L   N 

It works for the inorder traversal, but doesn't satisfy the preorder condition. I find it confusing due to the repeated letters.

My guess is that I'm using the wrong "G" as the root?

Thanks in advance!

Upvotes: 0

Views: 232

Answers (1)

trincot
trincot

Reputation: 351298

Indeed, the first G of the preorder happens to correspond here to the last G in the inorder, i.e. the root has no right subtree. This would fit:

         G
        /
       L
      / \
     O   O
    /   / \
   W   L   N
            \
             N
            /
           G
            \
             O

Upvotes: 1

Related Questions