![]() |
Given a Binary Tree, our task is to print all nodes that do not have a sibling (a sibling is a node with the same parent. In a Binary Tree, there can be at most one sibling). The root should not be printed as it cannot have a sibling. Example: Input: ![]() Input Output: 4 5 6 Using Iterative ApproachIn this approach we use a queue to perform a The root should not be printed as it (BFS) of the binary tree. I.e. for each node, it checks if the node has only one child. If a node has only one child, that child is added to the result list. After this, the function adds the left and right children of the current node to the queue for further processing. Example: In this example, we are using the Iterative Approach to print all nodes that do not have any siblings.
Output 4 5 6 Time Complexity: O(N), where N is the number of nodes in the tree. Each node is visited once. Space Complexity: O(N), due to the usage of the queue. Using Recursive ApproachIn this approach, we will use recursion to traverse the binary tree. Here for each node, we check if the node has only one child (either left or right). If a node has only one child, that child is printed. After that, the function recursively calls itself for the left and right children of the current node. Example: In this example, we are using the recursive approach to print all nodes that do not have any siblings.
Output 4 5 6 Time Complexity: O(N), where N is the number of nodes in the tree. Each node is visited once. Space Complexity: O(H), where H is the height of the tree, due to the recursion stack. |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 17 |