Check if a Binary Tree contains duplicate subtrees of size 2 or more

Pattern: Serialise and deserialise

medium

Give every subtree a key string built from its value and its children's keys, with a marker for empty children. Equal subtrees get equal keys. Keep a set of keys of subtrees with at least two nodes; seeing one again means a duplicate.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Return whether the tree contains two equal subtrees (same shape and values) with at least two nodes each. Single leaves do not count. The catalogue has no practice link for this one. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • How can you compare two subtrees in O(1)?
  • What must the key include besides values?
  • Why skip leaves?

Hints

    Brute force, and why it fails

    Compare every pair of subtrees with Same Tree: O(n³) in the worst case.

    The key insight

    A key computed bottom up is a fingerprint of each subtree, so one pass with a set finds repeats.

    Dry run

    keys(2,(4),(5))

    Tree [1, 2, 3, 4, 5, null, 2, null, null, null, null, 4, 5]. The subtree 2 → (4, 5) appears on the left.

    Step 1 of 3

    The plan

    key(n): if null: "#"
            k = "(" + n.val + "," + key(left) + "," + key(right) + ")"
            if n is not a leaf: if k in seen: found = true; add k
            return k
    

    Complexity

    Time
    O(n²)
    Space
    O(n²)

    Keys can be long; with numbered keys (each distinct key gets an id) it drops to O(n).

    Edge cases

    • Empty tree: false.
    • Only leaves repeat: false.
    • The whole tree cannot be its own duplicate.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        private Set<String> seen;
        private boolean found;
    
        public boolean dupSub(TreeNode root) {
            seen = new HashSet<>();
            found = false;
            key(root);
            return found;
        }
    
        private String key(TreeNode n) {            // a string that is the same exactly for equal subtrees
            if (n == null) return "#";
            String k = "(" + n.val + "," + key(n.left) + "," + key(n.right) + ")";
            if ((n.left != null || n.right != null) && !seen.add(k)) found = true;   // leaves alone do not count
            return k;
        }
    }

    C++

    class Solution {
    public:
        unordered_set<string> seen;
        bool found;
    
        bool dupSub(TreeNode* root) {
            seen.clear();
            found = false;
            key(root);
            return found;
        }
    
        string key(TreeNode* n) {                   // a string that is the same exactly for equal subtrees
            if (n == NULL) return "#";
            string k = "(" + to_string(n->val) + "," + key(n->left) + "," + key(n->right) + ")";
            if ((n->left != NULL || n->right != NULL) && !seen.insert(k).second) found = true;   // leaves do not count
            return k;
        }
    };

    Python

    class Solution:
        def dupSub(self, root) -> bool:
            seen, found = set(), False
    
            def key(n) -> str:                      # a string that is the same exactly for equal subtrees
                nonlocal found
                if n is None:
                    return "#"
                k = f"({n.val},{key(n.left)},{key(n.right)})"
                if n.left or n.right:               # leaves alone do not count
                    if k in seen:
                        found = True
                    seen.add(k)
                return k
    
            key(root)
            return found

    Common mistakes

    • Counting duplicate leaves.
    • Building keys without empty markers or separators.

    Similar problems