VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-a-node-is-an-internal-node-or-not/

⇱ Check if a node is an Internal Node or not - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if a node is an Internal Node or not

Last Updated : 28 Nov, 2023

Given a binary tree, for each node check whether it is an internal node or not.

Examples:

Input:

👁 tree1
Example-1


Output: Node A: True
Node B: True
Node C: False
Node D: False
Explanation: In this illustration, Node A possesses two child nodes (B and C) which categorizes it as a node. On the other hand, both Nodes B possess one child node D, and C is a leaf node since they lack any child nodes.

Input:


👁 tree2
Example-2



Output: Node X: True
Node Y: False
Node Z: False
Explanation: In this illustration, Node X possesses two child nodes (Y and Z) which categorizes it as a node. On the other hand, both Nodes Y and Z are leaf nodes since they lack any child nodes.

Approach: To solve the problem follow the below steps:

  • Traverse the tree starting from the root node.
  • For every encountered node, during traversal check if it has any child nodes or not.
  • If the node has at least one child classify it as an internal node; otherwise consider it a leaf node.
  • Check for at least one child if either left or right or both exist then the node is an internal node.

Below is the implementation of the above approach:


Output
True
True
False
False

Time Complexity: O(N), where N is the number of nodes in the tree.
Auxillary Space: O(H), where H is the height of the tree (due to the recursion stack).

Comment