Sibling Nodes

You have been given a Binary Tree of ‘N’ nodes, where the nodes have integer values. Your task is to print all nodes that don’t have a sibling node.

Note:
1. Node ‘U’ is said to be a sibling of node ‘V’ if and only if both ‘U’ and ‘V’ have the same parent.
2. Root 1 is a sibling node.
Input Format:
The first line contains an integer 'T' which denotes the number of test cases or queries to be run.

The first line of each test case contains elements of the tree in the level order form. 
The line consists of values of nodes separated by a single space. In case a node is null, we take -1 in its place.

For example, the input for the tree is depicted in the below image. 

1

1
3 8
5 2 7 -1
-1 -1 -1 -1 -1 -1

Explanation :

Level 1 :
The root node of the tree is 1

Level 2 :
Left child of 1 = 3
Right child of 1 = 8

Level 3 :
Left child of 3 = 5
Right child of 3 = 2
Left child of 8 =7
Right child of 8 =  null (-1)


Level 4 :
Left child of 5 = null (-1)
Right child of 5 = null (-1)
Left child of 2 = null (-1)
Right child of 2 = null (-1)
Left child of 7 = null (-1)
Right child of 7 = null (-1)

The first not-null node(of the previous level) is treated as the parent of the first two nodes of the current level. The second not-null node (of the previous level) is treated as the parent node for the next two nodes of the current level and so on.
The input ends when all nodes at the last level are null(-1).
Note :
The above format was just to provide clarity on how the input is formed for a given tree. 

The sequence will be put together in a single line separated by a single space. Hence, for the above-depicted tree, the input will be given as:
1 3 8 5 2 7 -1 -1 -1 -1 -1 -1 -1
Output Format:
For each test case, print a single line containing space-separated integers denoting all the node’s values that don’t have a sibling node in sorted order.

The output of each test case will be printed in a separate line.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 5
0 <= N <= 3000
0 <= node data <= 10 ^ 9 

Where 'T' is the number of test cases and 'N' is the number of nodes in the tree.   

Time limit: 1 sec.
CodingNinjas
author
2y
DFS Approach

The idea here is to use the fact that if a node of the binary tree has two child nodes, then both of them will be siblings to each other, and if a node of the binary tree has only one child, then that child will not have any sibling.

Example 

E:\coding ninjas\Phase 2\problem 19 - Siblings in binary tree\3.png

In above figure 1 has two children, so nodes 3 and 4 are siblings to each other. Also, 3 has only one child, i.e., 5 and 5 have no sibling node.


So, we will use a dfs function to find all the nodes that have a single child.

Algorithm :

  • Declare an empty array say, ‘answer’ to store all the nodes that don’t have a sibling node.
  • Call dfs function to store all nodes that don’t have a sibling in ‘answer’ array.
  • Sort the ‘answer’.
  • Finally, return the ‘answer’.

 

Description of DFS function

This function will take two arguments, first one is ‘node’, which denotes the current node, and second is the array ‘answer’ to store all the nodes that don’t have a sibling.

DFS(node, ‘answer’) : 

  • If ‘node’ equals NULL, then return.
  • If both left and right child of ‘node’ is not NULL, then recur for ‘node -> left’ and ‘node -> right’.
  • Else two conditions will occur:
  • If the right child of ‘node’ is not NULL, then add data of the right child to ‘answer’ and recur for ‘node ->right’.
  • If the left child of ‘node’ is not NULL, then add data of the left child to ‘answer’ and recur for ‘node -> left’.
  • If both, left and right child of a node are NULL, then break the recursion.
Space Complexity: O(n)Explanation:

O(N), where ‘N’ is the total number of nodes in the given binary tree.

 

In the worst case, when we have given a skew binary tree, we need O(N) extra space in the form of recursive calls.

Hence the overall space complexity will be O(N).

Time Complexity: O(n)Explanation:

O(N), where ‘N’ is the total number of nodes in the given binary tree.

 

In the worst case, we visit each node exactly once in the DFS function that takes O(N) time.

Hence, the overall time complexity will be O(N).


Python (3.5)
'''

Time Complexity: O(N)
Space Complexity: O(N)

Where N is the total number of nodes in the binary tree.
'''

# DFS function to store all nodes that don't have a sibling.
def dfs(node, answer):
if node == None:
return

# Store all single child nodes.
if node.left != None and node.right != None:
dfs(node.left, answer)
dfs(node.right, answer)

elif node.left != None:
answer.append(node.left.val)
dfs(node.left, answer)

elif node.right != None:
answer.append(node.right.val)
dfs(node.right, answer)

def siblingNodes(node):
answer = []

if node == None:
return answer

dfs(node, answer)

# Sort the answer.
answer.sort()

return answer

C++ (g++ 5.4)
/*

Time Complexity: O(N)
Space Complexity: O(N)

Where N is the total number of nodes in the binary tree.
*/

#include

// DFS function to store all nodes that don't have a sibling.
void dfs(TreeNode *node, vector &answer)
{
// Base case
if (node == NULL)
{
return;
}

// Store all single child nodes.
if (node->left != NULL and node->right != NULL)
{
dfs(node->left, answer);
dfs(node->right, answer);
}
else if (node->left != NULL)
{
answer.push_back(node->left->val);
dfs(node->left, answer);
}
else if (node->right != NULL)
{
answer.push_back(node->right->val);
dfs(node->right, answer);
}
}

vector siblingNodes(TreeNode *node)
{
vector answer;

if (node == NULL)
{
return answer;
}

dfs(node, answer);

// Sort the answer.
sort(answer.begin(), answer.end());

return answer;
}

Java (SE 1.8)
/*

Time Complexity: O(N)
Space Complexity: O(N)

Where N is the total number of nodes in the binary tree.
*/

import java.util.ArrayList;
import java.util.Collections;

public class Solution {
// DFS function to store all nodes that don't have a sibling.
public static void dfs(TreeNode node, ArrayList answer){
// Base case
if (node == null){
return;
}

// Store all single child nodes.
if (node.left != null &&node.right != null){
dfs(node.left, answer);
dfs(node.right, answer);
}
else if (node.left != null){
answer.add(node.left.data);
dfs(node.left, answer);
}
else if (node.right != null){
answer.add(node.right.data);
dfs(node.right, answer);
}
}

public static ArrayList siblingNodes(TreeNode root) {
ArrayList answer = new ArrayList();

if (root == null){
return answer;
}

dfs(root, answer);

// Sort the answer.
Collections.sort(answer);

return answer;
}
}
CodingNinjas
author
2y
BFS Approach

The idea here is to use a breadth-first search. We will calculate all single-child nodes using BFS. 

Algorithm : 

  • Declare an empty array say, ‘answer’ to store all nodes that don’t have a sibling node.
  • Declare an empty queue and push the root node of the binary tree to it.
  • Run a loop until the queue is not empty.
  • Pop the front element from the queue, say ‘current’.
  • If both, left and the right child of ‘node’ are not NULL, then push ‘node -> left’ and ‘node -> right’ in the queue.
  • Else two conditions will occur:
  • If the right child of ‘node’ is not NULL, then add data of the right child to ‘answer’ and push ‘node -> right’ in the queue.
  • If the left child of ‘node’ is not NULL, then add data of the left child to ‘answer’ and push ‘node -> left’ in the queue.
  • Sort the ‘answer’.
  • Finally, return the ‘answer’.
Space Complexity: O(n)Explanation:

O(N), where ‘N’ is the total number of nodes in the given binary tree.

 

In the worst case, we are using a queue that requires additional O(N) space as there can be O(N) nodes in the queue in the worst case.

So, the overall space complexity is O(N).

Time Complexity: O(n)Explanation:

O(N), where ‘N’ is the total number of nodes in the given binary tree.

 

We are visiting each node exactly once and it takes O(N) time.

Hence, the overall time complexity will be O(N).


C++ (g++ 5.4)
/*

Time Complexity: O(N)
Space Complexity: O(N)

Where N is the total number of nodes in the binary tree.
*/

#include

vector siblingNodes(TreeNode *node)
{
vector answer;

if (node == NULL)
{
return answer;
}
queue *> q;
q.push(node);

// Run a loop until queue is not empty.
while (q.empty() == false)
{
TreeNode *current = q.front();
q.pop();

// Push single child node to queue.
if (current->left != NULL and current->right != NULL)
{
q.push(current->left);
q.push(current->right);
}
else if (current->left != NULL)
{
answer.push_back(current->left->val);
q.push(current->left);
}
else if (current->right != NULL)
{
answer.push_back(current->right->val);
q.push(current->right);
}
}

// Sort the answer.
sort(answer.begin(), answer.end());

return answer;
}

Python (3.5)
'''

Time Complexity: O(N)
Space Complexity: O(N)

where N is the number of nodes in the binary tree.
'''

from collections import deque

def siblingNodes(node):
answer = []

if node == None:
return answer

q = deque()
q.append(node)

# Run a loop until the queue is not empty.
while len(q):
current = q.popleft()

if current.left != None and current.right != None:
q.append(current.left)
q.append(current.right)

elif current.left != None:
answer.append(current.left.val)
q.append(current.left)

elif current.right != None:
answer.append(current.right.val)
q.append(current.right)

# Sort the answer.
answer.sort()

return answer

Java (SE 1.8)
/*

Time Complexity: O(N)
Space Complexity: O(N)

Where N is the total number of nodes in the binary tree.
*/

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;

public class Solution {

public static ArrayList siblingNodes(TreeNode root) {
ArrayList answer = new ArrayList();

if (root == null){
return answer;
}

Queue> q = new LinkedList<>();
q.add(root);

// Run a loop until queue is not empty.
while (q.isEmpty() == false){
TreeNode current = q.poll();

// Push single child node to queue.
if (current.left != null && current.right != null){
q.add(current.left);
q.add(current.right);
}
else if (current.left != null){
answer.add(current.left.data);
q.add(current.left);
}
else if (current.right != null){
answer.add(current.right.data);
q.add(current.right);
}
}

// Sort the answer.
Collections.sort(answer);

return answer;
}
}
Help your peers!
Add answer anonymously...
Directi Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter