Sub topic 2
Rebuilding a Tree from Two Traversals
This chapter assumes you know recursion, object references, and the four traversal orders from earlier in the tutorial. It rebuilds trees from traversal lists, applies the same ideas to expression trees, and then covers search and insertion in a binary search tree (BST).
Rebuilding a tree from two traversals
A single traversal does not identify a binary tree. Two different trees can share one preorder sequence. A pair of sequences often does identify the tree, and the rule is simple:
- The preorder (or postorder) sequence gives the root.
- The inorder sequence splits the remaining keys into left and right subtrees.
Inorder plus preorder, or inorder plus postorder, determines the tree when keys are distinct. Preorder plus postorder does not, in general.
For example, take preorder A B D E C and inorder D B E A C. The first preorder key, A, is the root. In the inorder list, A sits at index 3, so D B E form the left subtree and C forms the right subtree.
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def build(pre, ino):
if not pre:
return None
root = Node(pre[0])
k = ino.index(pre[0])
root.left = build(pre[1:k + 1], ino[:k])
root.right = build(pre[k + 1:], ino[k + 1:])
return root
def postorder(node):
if node is None:
return []
return postorder(node.left) + postorder(node.right) + [node.key]
root = build(list("ABDEC"), list("DBEAC"))
print(postorder(root)) # ['D', 'E', 'B', 'C', 'A']Expression trees and their traversals
An expression tree stores an arithmetic expression. Operators are internal nodes, and operands are leaves. For (a + b) * c, the root is *, its left child is + with leaves a and b, and its right child is the leaf c.
The traversals produce the three standard notations:
| Traversal | Output | Notation |
|---|---|---|
| Preorder | `* + a b c` | Prefix |
| Inorder | `a + b * c` | Infix (needs parentheses to be exact) |
| Postorder | `a b + c *` | Postfix |
Postfix is the form a compiler or calculator evaluates with a stack.
The binary search tree property
A binary search tree is a binary tree in which every key in a node's left subtree is smaller than the node's key, and every key in its right subtree is larger. This property makes search fast, because each comparison discards one whole subtree.
Searching a BST
To search, start at the root. If the key matches, stop. If the key is smaller, go left. If it is larger, go right. The search ends when it reaches a match or falls off the tree.
def search(node, key):
while node and node.key != key:
node = node.left if key < node.key else node.right
return nodeEach step moves one level down, so the cost is proportional to the height of the tree.
Inserting into a BST
Insertion follows the same path as search. When the search reaches an empty spot, the new node goes there. Duplicate keys are ignored in this version.
def insert(node, key):
if node is None:
return Node(key)
if key < node.key:
node.left = insert(node.left, key)
elif key > node.key:
node.right = insert(node.right, key)
return nodeExercise
A tree has preorder A B D E C and inorder D B E A C. What is its postorder traversal?
Show answer
D E B C A. The rebuilt tree has root A, left subtree B(D, E), and right child C. Postorder visits left, then right, then the root, giving D E B C A.