KatInterview

652. Find Duplicate Subtrees

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find all duplicate subtrees in a given binary tree. Two subtrees are considered duplicates if they have the same structure and the same node values. For each set of duplicate subtrees, we only need to return the root node of one of them.

Solution

Find Duplicate Subtrees in Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[TreeNode]:
        self.key_to_id = {}
        self.id_to_count = {}
        self.result = []
        self.next_id = 1
        
        self.post_order(root)
        
        return self.result

    def post_order(self, node: Optional[TreeNode]) -> int:
        # Base case: null node has a special ID, e.g., 0
        if not node:
            return 0

        # Recursively find IDs for left and right subtrees
        left_id = self.post_order(node.left)
        right_id = self.post_order(node.right)

        # Create a unique key for the current subtree structure
        key = f"{node.val},{left_id},{right_id}"

        # Get or assign an ID for this subtree structure
        if key not in self.key_to_id:
            id = self.next_id
            self.key_to_id[key] = id
            self.next_id += 1
        else:
            id = self.key_to_id[key]

        # Increment the count for this ID
        self.id_to_count[id] = self.id_to_count.get(id, 0) + 1

        # If this is the second time we see this structure, it's a duplicate.
        # Add the node to the result list.
        if self.id_to_count[id] == 2:
            self.result.append(node)

        return id

Find Duplicate Subtrees in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    private int nextId;
    private Map<String, Integer> keyToId;
    private Map<Integer, Integer> idToCount;
    private List<TreeNode> result;

    public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
        nextId = 1;
        keyToId = new HashMap<>();
        idToCount = new HashMap<>();
        result = new ArrayList<>();
        postOrder(root);
        return result;
    }

    private int postOrder(TreeNode node) {
        // Base case: null node has a special ID, e.g., 0
        if (node == null) {
            return 0;
        }

        // Recursively find IDs for left and right subtrees
        int leftId = postOrder(node.left);
        int rightId = postOrder(node.right);

        // Create a unique key for the current subtree structure
        String key = node.val + "," + leftId + "," + rightId;

        // Get or assign an ID for this subtree structure
        int id = keyToId.computeIfAbsent(key, k -> nextId++);
        
        // Increment the count for this ID
        idToCount.put(id, idToCount.getOrDefault(id, 0) + 1);

        // If this is the second time we see this structure, it's a duplicate.
        // Add the node to the result list.
        if (idToCount.get(id) == 2) {
            result.add(node);
        }

        return id;
    }
}

Find Duplicate Subtrees in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
        vector<TreeNode*> result;
        unordered_map<string, int> key_to_id;
        unordered_map<int, int> id_to_count;
        int next_id = 1;
        postOrder(root, key_to_id, id_to_count, result, next_id);
        return result;
    }

private:
    int postOrder(TreeNode* node, unordered_map<string, int>& key_to_id, unordered_map<int, int>& id_to_count, vector<TreeNode*>& result, int& next_id) {
        // Base case: null node has a special ID, e.g., 0
        if (!node) {
            return 0;
        }

        // Recursively find IDs for left and right subtrees
        int left_id = postOrder(node->left, key_to_id, id_to_count, result, next_id);
        int right_id = postOrder(node->right, key_to_id, id_to_count, result, next_id);

        // Create a unique key for the current subtree structure
        string key = to_string(node->val) + "," + to_string(left_id) + "," + to_string(right_id);

        int id;
        // If this subtree structure is seen for the first time
        if (key_to_id.find(key) == key_to_id.end()) {
            id = next_id++;
            key_to_id[key] = id;
            id_to_count[id] = 1;
        } else {
            // This structure has been seen before
            id = key_to_id[key];
            id_to_count[id]++;
            // If this is the second time we see this structure, it's a duplicate.
            // Add the node to the result list.
            if (id_to_count[id] == 2) {
                result.push_back(node);
            }
        }

        return id;
    }
};

Find Duplicate Subtrees in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function findDuplicateSubtrees(root: TreeNode | null): Array<TreeNode | null> {
    const keyToId = new Map<string, number>();
    const idToCount = new Map<number, number>();
    const result: TreeNode[] = [];
    let nextId = 1;

    function postOrder(node: TreeNode | null): number {
        // Base case: null node has a special ID, e.g., 0
        if (node === null) {
            return 0;
        }

        // Recursively find IDs for left and right subtrees
        const leftId = postOrder(node.left);
        const rightId = postOrder(node.right);

        // Create a unique key for the current subtree structure
        const key = `${node.val},${leftId},${rightId}`;

        let id: number;
        // Get or assign an ID for this subtree structure
        if (!keyToId.has(key)) {
            id = nextId++;
            keyToId.set(key, id);
        } else {
            id = keyToId.get(key)!;
        }

        // Increment the count for this ID
        const count = (idToCount.get(id) || 0) + 1;
        idToCount.set(id, count);

        // If this is the second time we see this structure, it's a duplicate.
        // Add the node to the result list.
        if (count === 2) {
            result.push(node);
        }

        return id;
    }

    postOrder(root);
    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.