Copying and comparing trees
Two short recursive algorithms: copy a binary tree node by node, and check whether two trees have the same shape and the same keys; both O(n).
A binary tree is copied with a preorder traversal: make a new node with the same key, then copy the left and right
subtrees recursively and attach them. Each node is copied once: O(n).
- Time:
O(n) - Space:
O(h) for the recursion - Horowitz–Sahni, chapter 5
A and B are the same keys in two insertion orders that give the same tree; a is copied, and a and b are equal.
class Node:def __init__(self, key):self.key = keyself.left = Noneself.right = Nonedef copy_and_compare(A, B):a = build(A[0])b = build(B[0])c = copy(a)same = equal(a, b)return samedef copy(node):if node is None:return Nonet = Node(node.key)t.left = copy(node.left)t.right = copy(node.right)return tdef equal(x, y):if x is None and y is None:return Trueif x is None or y is None:return Falseif x.key != y.key:return Falsematch = x.keyreturn equal(x.left, y.left) and equal(x.right, y.right)def build(keys):# A binary search tree from the keys in this insertion order.root = Nonefor k in keys:node = Node(k)if root is None:root = nodecontinuep = rootwhile True:if k < p.key:if p.left is None:p.left = nodebreakp = p.leftelse:if p.right is None:p.right = nodebreakp = p.rightreturn root
Start
∅
∅
∅
Recursion tree
Filled orange = running call · Orange outline = still on the stack · Grey = finished
Local variables
Orange = changed in this step
A list
B list
Call stack
- copy_and_compare()line 8
Explanation
Copying
A binary tree is copied with a preorder traversal: make a new node with the same key, then copy the left and right
subtrees recursively and attach them. Each node is copied once: O(n).
Equality
Two trees are equal if both are empty, or their roots have the same key and their left and right subtrees are (recursively) equal. The answer is "no" at the first difference, in shape or in a key.
A note
The same keys inserted in different orders can give the same binary search tree or a different one; the presets show both.
The input
A and B are the insertion orders of the keys into two binary search trees, a and b.