Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uniqueness of Inorder, Preorder, and Postorder traversal with null elements

Tags:

algorithm

tree

We all know that different binary trees can have the same inorder, preorder, or postorder traversal. But if we were to include null elements into a preorder traversal, then result of the traversal would be unique as long as the trees are unique. Consider these two trees:

  3                      3
 /                        \
4            vs.           4

Their normal preorder traversal would be {3,4} for both, but if we were to include null elements, then their traversal would be {3,4,null,null,null} and {3,null,4,null,null} respectfully, making the traversal unique.

My question is, would this be true for inorder and postorder traversals as well? And how can we prove it?

like image 263
bli00 Avatar asked Aug 24 '17 21:08

bli00


People also ask

Are preorder traversals unique?

Preorder and postorder do not uniquely define a binary tree. Scan the preorder left to right using the inorder to separate left and right subtrees. a is the root of the tree; gdhbei are in the left subtree; fjc are in the right subtree.

Is inorder traversal unique for a binary tree?

It depends on what traversals are given. If one of the traversal methods is Inorder then the tree can be constructed, otherwise not. Therefore, following combination can uniquely identify a tree. Inorder and Preorder.

Is preorder traversal unique for BST?

Consider the case when we can have no right sub-tree from the root. Then, the traversal will go into the leftsubtree directly and the last node will be in the left sub-tree and is not the rightmost node. Therefore, we cannot create a unique Binary Tree using Preorder.

What is the difference between inorder preorder and postorder traversal?

For Inorder, you traverse from the left subtree to the root then to the right subtree. For Preorder, you traverse from the root to the left subtree then to the right subtree. For Post order, you traverse from the left subtree to the right subtree then to the root.


1 Answers

It is true for a postorder traversal, because that's just the reverse of the preorder traversal of the reversed tree.

It is NOT true for an inorder traversal, which would always start with null, end with null, and alternate between nulls and nodes.

E.g., these trees:

  B          D    
 / \        / \
A   D      B   E
   / \    / \
  C   E  A   C

both produce

null, A, null, B, null, C, null, D, null, E, null
like image 103
Matt Timmermans Avatar answered Nov 16 '22 01:11

Matt Timmermans