Unival Trees Problem Statement
You are given a binary tree. Your task is to return the count of unival sub-trees in the given binary tree. In a unival tree, all nodes below the root node have the same value as the root node.
Example:
Consider the binary tree given in the following diagram, the number of unival trees is 5.
Input:
The first line of input contains an integer T, the number of test cases.
The next T lines, where each line contains elements in level order form. The input consists of values of nodes separated by a single space in a single line. In case a node is null, we take -1 in its place.
For example, the input for the tree depicted in the below image would be:
1
2 3
4 -1 5 6
-1 7 -1 -1 -1 -1
-1 -1
Output:
For every test case, print a single line containing an integer, i.e., the count of unival trees.
Example:
Input:
1
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
Output:
5
Constraints:
- 1 <= T <= 10
- 0 <= N <= 10^5
- 0 <= data <= 10^4, where data is the value for a node.
- Time Limit: 1 sec
Note:
The above format was just to provide clarity on how the input is formed for a given tree. The sequence will be put together in a single line separated by a single space. Hence, for the above depicted tree, the input will be given as:
1
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
You do not need to print anything; it has already been taken care of. Just implement the given function.

AnswerBot
4mo
Count the number of unival sub-trees in a binary tree where all nodes below the root have the same value as the root node.
Traverse the binary tree recursively and check if each subtree is a unival tre...read more
Help your peers!
Add answer anonymously...
Infosys Software Developer interview questions & answers
A Software Developer was asked 1mo agoQ. Introduce the project.
A Software Developer was asked 1mo agoQ. What do you know about Infosys services and solutions?
A Software Developer was asked 4mo agoQ. What are the different app states in an iOS application?
Popular interview questions of Software Developer
A Software Developer was asked 1mo agoQ1. Introduce the project.
A Software Developer was asked 1mo agoQ2. What do you know about Infosys services and solutions?
A Software Developer was asked 4mo agoQ3. What are the different app states in an iOS application?
Top HR questions asked in Infosys Software Developer
A Software Developer was asked 1mo agoQ1. How do you think you can contribute to Infosys' growth?
A Software Developer was asked 1mo agoQ2. Why do you want to work for Infosys?
A Software Developer was asked 1mo agoQ3. What was your role in the project you completed?
Stay ahead in your career. Get AmbitionBox app


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
AmbitionBox Awards
Get AmbitionBox app

