Check if subtree
Submissions: 10599   Accuracy:

41.56%

  Difficulty: Medium   Marks: 4
     

Given two binary trees with head reference as T and S having at most N nodes. The task is to check if S is present as subtree in T.
A subtree of a tree T1 is a tree T2 consisting of a node in T1 and all of its descendants in T1.

Example:

S:          10
              /   \
            4     6
                 /
             30

T:                  26
                      /   \
                    10   3
                   /   \     \

               4       6     3
                       /
                    30

In above example S is subtree of T.

Input:
First line of input contains number of testcases T. For each testcase, there will be two lines, first of which containing the number of edges (between two nodes) in the tree. Next line contains N pairs (considering a and b) with a 'L' (means node b on left of a) or 'R' (means node b on right of a) after a and b.

Output:
For each testcase, there will be a single line containing 0 or 1, depending on the input.

Constraints:
1 <= T <= 30
1 <= N <= 103

Example:
Input:
2
5
26 10 L 10 20 L 10 30 R 20 40 L 20 60 R
5
26 10 L 10 20 L 10 30 R 20 40 L 20 60 R

3
10 4 L 10 6 R 4 30 R
6
26 10 L 26 3 R 10 4 L 10 6 R 6 25 R 3 3 R

Output:
1
0

Explanation:
Testcase 2:
Structure of tree:

10 4 L 10 6 R 4 30 R
10 is root node of tree. Left child of 10 is 4 and right child of 10 is 6. Right child of 4 is 30.

 

** For More Input/Output Examples Use 'Expected Output' option **

Contributor: Harshit Sidhwa
Author: mabhinav


Need help with your code? Please use ide.geeksforgeeks.org, generate link and share the link here.

to report an issue on this page.