Validate Binary Tree Nodes
You are given ‘N’ binary tree nodes numbered from 0 to N - 1 where node ‘i’ has two children LEFT_CHILD[i] and RIGHT_CODE[i]. Return ‘True’ if and only if all the given nodes form exactly one valid binary tree. If node ‘i’ has no left child then 'LEFT_CHILD[i]' will equal -1, similarly for the right child.
Example:
Let’s say we have n=4 nodes, 'LEFT_CHILD' = {1, -1, 3, -1} and
RIGHT_CHILD = {2, -1, -1, -1}. So the resulting tree will look like this:
It will return True as there is only one valid binary tree and each node has only one parent and there is only one root.
Input format:
The very first line of input contains an integer ‘T’ denoting the
number of test cases.
The first line of every test case contains an integer ‘N’ denoting
the number of nodes of the tree.
The next two lines of every test case contain the 'LEFT_CHILD' array and
'RIGHT_CHILD' array respectively.
Output format:
For each test case, return either ‘Yes’ or ‘No’ that whether from given nodes, we can form exactly one valid binary tree or not.
Output for each test case is printed on a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just return ‘True’ or ‘False’ that whether from given nodes we can form exactly one valid binary tree or not.
The nodes have no values and that we only use the node numbers in this problem.
Constraints:
1 <= T <= 10
1 <= N <= 10^4
LEFT_CHILD.length == RIGHT_CHILD.length == N
-1 <= LEFT_CHILD[i], RIGHT_CHILD[i] <= N - 1
Time Limit: 1 sec
AnswerBot
1y
The task is to determine if the given binary tree nodes form exactly one valid binary tree.
Check if there is only one root node (a node with no parent)
Check if each node has at most one parent
Check if...read more
CodingNinjas
author
2y
I used level order traversal concept to solve this problem
CodingNinjas
author
2y
Validate Binary Tree Nodes
Approach:
- In this approach, we have to check three things:
- The count of the parent of each node should one
- The count of the possible root should be one and if there exists a po...read more
Add answer anonymously...
Top Josh Technology Group Software Developer interview questions & answers
Popular interview questions of Software Developer
>
Josh Technology Group Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app