Subtree Check in Binary Trees

You are given two binary trees, T and S. Your task is to determine whether tree S is a subtree of tree T, meaning S must match the structure and node values of some subtree in T.

Input:

The first line contains an integer ‘T’, indicating the number of test cases.

Each test case has two subsequent lines:
1. The first line holds the level order traversal of tree T, with node values separated by a space. Replace null nodes with -1.
2. The second line holds the level order traversal of tree S, similarly formatted.

Output:

For each test case, output a single line with 'true' if S is a subtree of T; otherwise, 'false'.

Example:

Input:
1
2 3
4 -1 5 6
-1 7 -1 -1 -1 -1
-1 -1
Output:
true

Constraints:

  • 1 ≤ T ≤ 100
  • 1 ≤ N, M ≤ 1000
  • 0 ≤ data ≤ 106, and data ≠ -1

Note:

The input format provided above elaborates on how to parse the tree in a single line, substituting null (-1) for non-existent nodes.
AnswerBot
4mo

The task is to determine whether tree S is a subtree of tree T, matching structure and node values.

  • Parse the input level order traversal of both trees T and S

  • Check if tree S is a subtree of tree T by ...read more

Help your peers!
Select
Add answer anonymously...

Snapdeal Software Developer interview questions & answers

A Software Developer was asked Q. Given two linked lists that merge at a point, find the merging point.
A Software Developer was asked Q. Given an M x N matrix, how many rectangles are there?
A Software Developer was asked Q. Find a four-digit number in the form aabb that is a perfect square.

Popular interview questions of Software Developer

A Software Developer was asked Q1. Given two linked lists that merge at a point, find the merging point.
A Software Developer was asked Q2. Given an M x N matrix, how many rectangles are there?
A Software Developer was asked Q3. Find a four-digit number in the form aabb that is a perfect square.
Snapdeal 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