Update appNew update is available. Click here to update.
sidenav-btnClose
Topic list
Validate Binary Tree Nodes
MEDIUM
15 mins
6 upvotes
Graph
Topics (Covered in this problem)
Problem solved
Badge
Skill meter
Graph
-
-
Other topics
Problem solved
Badge
Skill meter
Strings
-
-
Matrices (2D Arrays)
-
-
Linked List
-
-
Sorting
-
-
Binary Search
-
-
Stacks & Queues
-
-
Trees
-
-
Dynamic Programming
-
-
Greedy
-
-
Tries
-
-
Arrays
-
-
SQL
-
-
Binary Search Trees
-
-
Heap
-
-
Bit Manipulation
-
-
Solve problems & track your progress
Checkout your overall progress in every topic here
Become
userLevel
Sensei
in DSA topics
Open the topic and solve more problems associated with it to improve your skills
Check out the skill meter for every topic
See how many problems you are left with to solve for cracking any stage. Score more than zero to get your progress counted.

Validate Binary Tree Nodes

Contributed by
Dhruv Sharma
Medium
yellow-spark
0/80
Avg time to solve 15 mins
Success Rate 85 %
Share
6 upvotes

Problem Statement

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.
Detailed explanation ( Input/output format, Notes, Constraints, Images )
Sample Input 1:
2
4
1 -1 3 -1
2 -1 -1 -1
4
1 -1 3 -1
2 3 -1 -1
Sample Output 1:
Yes
No
Explanation 1:
For the first test case, 
It is already explained above in the example.

For the second test case, 
The resulting tree from the given input will be :

So the output will be ‘False’ because node 3 has two parents 1 
and 2.
Sample Input 2:
2
2
1 0
-1 -1
6
1 -1 -1 4 -1 -1
2 -1 -1 5 -1 -1
Sample Output 2:
 No
 No
Reset Code
Full screen
Auto
copy-code
Console