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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With