Given a Binary Tree of n nodes, the task is to find all the nodes that don't have any siblings. Return a list of integers containing all the nodes that don't have a sibling in sorted order (Increasing).
Two nodes are said to be siblings if they are present at the same level, and their parents are the same.
[Expeacted Approach - 1] Using Recursion - O(nlogn) Time and O(n) Space
The idea is to recursively traverse the binary tree. For each node, if both its child nodes exists, then process both the left and right subtrees. If only left subtree exists, then append its value to the result and process it recursively. If only right subtree exists, then append its value to the result, and process it recursively. Finally sort the resultant array and return it.
Below is the implementation of the above approach:
Output
4 5 6
Time Complexity: O(nlogn), time taken to sort the resultant array. Space Complexity:O(n), where n is the number of nodes in tree.
[Expected Approach - 2] Using Queue - O(nlogn) Time and O(n) Space
The idea is to use level order traversal to traverse the nodes. For each node, If both its child nodes exists, then push both the nodes into the queue. If one of the child nodes exists, then append the child node into the resultant list and push it into the queue.
Below is the implementation of the above approach:
Output
4 5 6
Time Complexity: (nlogn), time taken to sort the resultant array. Auxiliary Space: O(n), where n is the number of nodes in tree.