Duplicate Subtrees Problem Statement

Given a binary tree, return the root values of all duplicate subtrees. Two subtrees are considered duplicate if they have the same structure with identical node values. For each duplicate subtree, return the root value of any one of them.

Example:

Tree:
 Consider the following binary tree: alt text 
Output:
{2, 3}
Explanation:

The duplicate subtrees are {{2, 3}, {3}}, hence the root values are {2, 3}. The order doesn't matter.

Input:

T, then each test case with nodes in level order, using -1 for null nodes.
Example for one tree: 1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1

Output:

Space-separated root values of all duplicate subtrees for each test case in separate lines. Use -1 if no duplicates.

Constraints:

  • 1 <= T <= 5
  • 1 <= N <= 100
  • 1 <= val <= 105
  • Time Limit: 1 sec
Note:
The input for the tree is given as a single sequence of space-separated values.
AnswerBot
4mo

Find root values of duplicate subtrees in a binary tree.

  • Traverse the tree in a bottom-up manner to identify duplicate subtrees.

  • Use a hashmap to store the subtree structure and count occurrences.

  • Return...read more

Help your peers!
Select
Add answer anonymously...

Nagarro Software Developer interview questions & answers

A Software Developer was asked 3mo agoQ. Design and implement a data structure for Least Recently Used (LRU) cache. It sh...read more
A Software Developer was asked 3mo agoQ. Given the root of a binary search tree, and an integer k, return the kth smalles...read more
A Software Developer was asked 5mo agoQ. What is abstraction in Java?

Popular interview questions of Software Developer

A Software Developer was asked 3mo agoQ1. Design and implement a data structure for Least Recently Used (LRU) cache. It sh...read more
A Software Developer was asked 3mo agoQ2. Given the root of a binary search tree, and an integer k, return the kth smalles...read more
A Software Developer was asked 5mo agoQ3. What is abstraction in Java?
Nagarro Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits