![]() |
VOOZH | about |
Given N nodes numbered from 0 to n-1, also given the E number of directed edges, determine whether the given nodes all together form a single binary tree or not.
Examples:
Input: N = 4, edges[][] = [[0 1], [0 2], [2 3]]
Output: true
Explanation: Form a single binary tree with a unique root node.Input: N = 4, edges[][] = [[0 1], [0 2], [1 3], [2 3]]
Output: false
Explanation: Not form a single binary tree because they contain a cycle.
Approach: To solve the problem follow the below idea:
To determine if the given nodes form a single binary tree, you can use a Depth-First Search (DFS) algorithm to traverse the graph and check for the following conditions:
- The Graph should be connected
- There should be exactly one node with an in-degree of 0, which will be the root of the binary tree.
- Every other node should have an in-degree of 1 , except for the root node, which should have an in-degree of 0.
- Also for each node the number of childrens should be less than equal to 2.
Steps to Solve the problem:
Below is the implementation of the above idea:
false
Time complexity: O(N + E), where N is the number of nodes and E is the number of edges.
Auxiliar Space: O(N + E), where N is the number of nodes and E is the number of edges.