Algorithmstree node copying

Tree Node Copying — Clone a Binary Tree

TT
Testlaa Team
May 14, 20261 min read

Copy each node and wire children recursively; if random pointers exist, use a hash map from old→new before second pass.

Try this in Python

from __future__ import annotations
from dataclasses import dataclass


@dataclass
class TreeNode:
    val: int
    left: TreeNode | None = None
    right: TreeNode | None = None


def clone(root: TreeNode | None) -> TreeNode | None:
    if not root:
        return None
    return TreeNode(root.val, clone(root.left), clone(root.right))

r = TreeNode(1, TreeNode(2), TreeNode(3))
c = clone(r)
print(c.val, c.left.val if c.left else None)

Key takeaways

  • Deep copy is default meaning of “clone tree” without extra pointers.
  • Iterative clone can use stack mirroring traversals.
  • Remember to not alias original nodes unless sharing is intended.

Tags:

Tree structuresPythonStudents