VOOZH about

URL: https://www.geeksforgeeks.org/dsa/validate-the-binary-tree-nodes/

⇱ Validate the Binary Tree Nodes - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Validate the Binary Tree Nodes

Last Updated : 23 Jul, 2025

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:

  • In a binary tree, every node (except the root) should have one parent.
  • We can use an unordered_map called inDegree to store the in-degree of each node.
  • If any node has an in-degree greater than 1, it means it has more than one parent, which violates the binary tree condition rule.
  • Similarly, for each parent node, we need to count the number of children it has.
  • If any node has more than two children, it also violates the binary tree condition. We use another unordered_map called childrenCount to keep track of this.
  • A binary tree should have exactly one root node. We count the number of nodes with an in-degree of 0.
  • If there is more than one such node, it means there is more than one root, which is not allowed in a binary tree.

Below is the implementation of the above idea:


Output
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.

Comment