Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Trees/Tree Construction & Serialization

Technique · Interview · medium

Tree Hashing / Canonical Forms

Give each subtree a canonical id: map its sorted tuple of child ids through a hash map, or use a randomised polynomial hash. Equal shapes then get equal ids. Unrooted trees are compared by rooting at their centre(s).

Learn firstTree DFS (Paths & Recursion)Hash Map / Hash Set LookupTree Construction & Serialization
0%
mastery
0/4 solved
Practise nextFind Duplicate Subtrees
IdeaPracticePitfalls

Recognise it

The signal

find duplicate subtrees

  1. 1Brute force

    Compare every pair of subtrees: O(n2) or worse.

  2. 2The observation

    Repeated structural comparison.

  3. 3Why it works

    Two rooted subtrees are isomorphic iff their canonical ids are equal. This is exact with the map-of-sorted-children method.

Reach for it when

  • +are two trees isomorphic (rooted or unrooted)
  • +count distinct subtree shapes

Not when

  • ×you need the actual node matching (record it while merging ids)

Practice

Next

Find Duplicate Subtrees

0/4 solved
  • Subtree of Another TreeMeta, AmazonEasy
  • Find Duplicate SubtreesMedium
  • Tree Isomorphism ICSESMedium
  • Tree Isomorphism IICSESMedium

Pitfalls

Misconceptions

  • !serializing without separators/null markers causes collisions
  • !for unrooted trees, root at the centre and try both centres when there are two
Go deeper1 combinations · resources

Combinations

  • Tree Hashing / Canonical Forms+Topological Sort

    are two unrooted trees isomorphic

    Tree Hashing / Canonical Forms:
    a canonical id of the tree rooted at each centre
    Topological Sort:
    leaf trimming finds the 1-2 centres of an unrooted tree

    Tree Isomorphism II

Resources

  • Binary Tree explore cardLeetCode · course
  • Tree cheatsheetTech Interview Handbook · article
  • BST visualizerVisuAlgo · tool
  • Introduction to Tree AlgorithmsUSACO Guide · course
  • Lowest Common Ancestorcp-algorithms · article
  • NeetCode RoadmapNeetCode · sheet
TodayReviewPatternsProblems