AlgoVerse

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).

Read the full explanation ↓
Input:
A 1×6 · B 1×6PDF export

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.

  1. class Node:
  2. def __init__(self, key):
  3. self.key = key
  4. self.left = None
  5. self.right = None
  6. def copy_and_compare(A, B):
  7. a = build(A[0])
  8. b = build(B[0])
  9. c = copy(a)
  10. same = equal(a, b)
  11. return same
  12. def copy(node):
  13. if node is None:
  14. return None
  15. t = Node(node.key)
  16. t.left = copy(node.left)
  17. t.right = copy(node.right)
  18. return t
  19. def equal(x, y):
  20. if x is None and y is None:
  21. return True
  22. if x is None or y is None:
  23. return False
  24. if x.key != y.key:
  25. return False
  26. match = x.key
  27. return equal(x.left, y.left) and equal(x.right, y.right)
  28. def build(keys):
  29. # A binary search tree from the keys in this insertion order.
  30. root = None
  31. for k in keys:
  32. node = Node(k)
  33. if root is None:
  34. root = node
  35. continue
  36. p = root
  37. while True:
  38. if k < p.key:
  39. if p.left is None:
  40. p.left = node
  41. break
  42. p = p.left
  43. else:
  44. if p.right is None:
  45. p.right = node
  46. break
  47. p = p.right
  48. return root

Invariant: EQUAL(x, y) is true exactly when the subtrees at x and y have the same shape and the same keys.

Start

a

∅

b

∅

c

∅

same—

Recursion tree

Filled orange = running call · Orange outline = still on the stack · Grey = finished

Local variables

Orange = changed in this step

A list

[8, 4, 12, 2, 6, 10]

B list

[8, 12, 4, 10, 6, 2]

Call stack

  1. copy_and_compare()line 8
Step 1 of 324
Black = copy_node, same_key · Orange = key stepbuilt: 0/1 · copy_node: 0/6 · copied: 0/1 · same_key: 0/6 · compared: 0/1
    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.