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:
C++
// C++ Program to find nodes with no // siblings in a given binary tree#include<bits/stdc++.h>usingnamespacestd;classNode{public:Node*left,*right;intdata;Node(intx){data=x;left=nullptr;right=nullptr;}};voidnoSiblingRecur(Node*node,vector<int>&ans){// base caseif(node==nullptr)return;// If this is an internal node, recur for left// and right subtreesif(node->left!=nullptr&&node->right!=nullptr){noSiblingRecur(node->left,ans);noSiblingRecur(node->right,ans);}// If only left child exists, then// append it to result and recur.elseif(node->left!=nullptr){ans.push_back(node->left->data);noSiblingRecur(node->left,ans);}// If only right child exists, then// append it to result and recur.elseif(node->right!=nullptr){ans.push_back(node->right->data);noSiblingRecur(node->right,ans);}}vector<int>noSibling(Node*node){vector<int>ans;noSiblingRecur(node,ans);// if there are 0 nodes// without any siblingsif(ans.empty())ans.push_back(-1);// else sort the resultelsesort(ans.begin(),ans.end());returnans;}voidprintList(vector<int>v){intn=v.size();for(inti=0;i<n;i++){cout<<v[i]<<" ";}cout<<endl;}intmain(){// Create a hard coded binary tree// 1// / \ // 2 3 // \ /// 4 5 // /// 6Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->right=newNode(4);root->right->left=newNode(5);root->right->left->left=newNode(6);vector<int>ans=noSibling(root);printList(ans);return0;}
Java
// Java Program to find nodes with no// siblings in a given binary treeimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{staticvoidnoSiblingRecur(Nodenode,ArrayList<Integer>ans){// base caseif(node==null)return;// If this is an internal node, recur for left// and right subtreesif(node.left!=null&&node.right!=null){noSiblingRecur(node.left,ans);noSiblingRecur(node.right,ans);}// If only left child exists, then// append it to result and recur.elseif(node.left!=null){ans.add(node.left.data);noSiblingRecur(node.left,ans);}// If only right child exists, then// append it to result and recur.elseif(node.right!=null){ans.add(node.right.data);noSiblingRecur(node.right,ans);}}staticArrayList<Integer>noSibling(Nodenode){ArrayList<Integer>ans=newArrayList<Integer>();noSiblingRecur(node,ans);// if there are 0 nodes// without any siblingsif(ans.isEmpty())ans.add(-1);// else sort the resultelseCollections.sort(ans);returnans;}staticvoidprintList(ArrayList<Integer>v){for(inti:v){System.out.print(i+" ");}System.out.println();}publicstaticvoidmain(String[]args){// Create a hard coded binary tree// 1// / \// 2 3// \ /// 4 5// /// 6Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.right=newNode(4);root.right.left=newNode(5);root.right.left.left=newNode(6);ArrayList<Integer>ans=noSibling(root);printList(ans);}}
Python
# Python Program to find nodes with no# siblings in a given binary treeclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=NonedefnoSiblingRecur(node,ans):# base caseifnotnode:return# If this is an internal node, recur for left# and right subtreesifnode.leftandnode.right:noSiblingRecur(node.left,ans)noSiblingRecur(node.right,ans)# If only left child exists, then# append it to result and recur.elifnode.left:ans.append(node.left.data)noSiblingRecur(node.left,ans)# If only right child exists, then# append it to result and recur.elifnode.right:ans.append(node.right.data)noSiblingRecur(node.right,ans)defnoSibling(node):ans=[]noSiblingRecur(node,ans)# if there are 0 nodes# without any siblingsifnotans:ans.append(-1)# else sort the resultelse:ans.sort()returnansdefprintList(v):print(" ".join(map(str,v)))if__name__=="__main__":# Create a hard coded binary tree# 1# / \# 2 3# \ /# 4 5# /# 6root=Node(1)root.left=Node(2)root.right=Node(3)root.left.right=Node(4)root.right.left=Node(5)root.right.left.left=Node(6)ans=noSibling(root)printList(ans)
C#
// C# Program to find nodes with no// siblings in a given binary treeusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{staticvoidNoSiblingRecur(Nodenode,List<int>ans){// base caseif(node==null)return;// If this is an internal node, recur for left// and right subtreesif(node.left!=null&&node.right!=null){NoSiblingRecur(node.left,ans);NoSiblingRecur(node.right,ans);}// If only left child exists, then// append it to result and recur.elseif(node.left!=null){ans.Add(node.left.data);NoSiblingRecur(node.left,ans);}// If only right child exists, then// append it to result and recur.elseif(node.right!=null){ans.Add(node.right.data);NoSiblingRecur(node.right,ans);}}staticList<int>NoSibling(Nodenode){List<int>ans=newList<int>();NoSiblingRecur(node,ans);// if there are 0 nodes// without any siblingsif(ans.Count==0)ans.Add(-1);// else sort the resultelseans.Sort();returnans;}staticvoidPrintList(List<int>v){foreach(intiinv){Console.Write(i+" ");}Console.WriteLine();}staticvoidMain(string[]args){// Create a hard coded binary tree// 1// / \// 2 3// \ /// 4 5// /// 6Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.right=newNode(4);root.right.left=newNode(5);root.right.left.left=newNode(6);List<int>ans=NoSibling(root);PrintList(ans);}}
JavaScript
// JavaScript Program to find nodes with no// siblings in a given binary treeclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}functionnoSiblingRecur(node,ans){// base caseif(!node)return;// If this is an internal node, recur for left// and right subtreesif(node.left&&node.right){noSiblingRecur(node.left,ans);noSiblingRecur(node.right,ans);}// If only left child exists, then// append it to result and recur.elseif(node.left){ans.push(node.left.data);noSiblingRecur(node.left,ans);}// If only right child exists, then// append it to result and recur.elseif(node.right){ans.push(node.right.data);noSiblingRecur(node.right,ans);}}functionnoSibling(node){letans=[];noSiblingRecur(node,ans);// if there are 0 nodes// without any siblingsif(ans.length===0)ans.push(-1);// else sort the resultelseans.sort((a,b)=>a-b);returnans;}functionprintList(v){console.log(v.join(" "));}// Create a hard coded binary tree// 1// / \// 2 3// \ /// 4 5// /// 6constroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.right=newNode(4);root.right.left=newNode(5);root.right.left.left=newNode(6);constans=noSibling(root);printList(ans);
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:
C++
// C++ Program to find nodes with no // siblings in a given binary tree#include<bits/stdc++.h>usingnamespacestd;classNode{public:Node*left,*right;intdata;Node(intx){data=x;left=nullptr;right=nullptr;}};vector<int>noSibling(Node*node){if(node==nullptr)return{-1};// create an empty result arrayvector<int>ans;queue<Node*>q;q.push(node);while(!q.empty()){Node*curr=q.front();q.pop();// If this is an internal node, push the left// and right nodes into queueif(curr->left!=nullptr&&curr->right!=nullptr){q.push(curr->left);q.push(curr->right);}// If left child is NULL and right is not, // append right node into result and push// it into queue.elseif(curr->right!=nullptr){ans.push_back(curr->right->data);q.push(curr->right);}// If right child is NULL and left is // not, append left child to result// and push left node into queue.elseif(curr->left!=nullptr){ans.push_back(curr->left->data);q.push(curr->left);}}// if there are 0 nodes// without any siblingsif(ans.empty())ans.push_back(-1);// else sort the resultelsesort(ans.begin(),ans.end());returnans;}voidprintList(vector<int>v){intn=v.size();for(inti=0;i<n;i++){cout<<v[i]<<" ";}cout<<endl;}intmain(){// Create a hard coded binary tree// 1// / \ // 2 3 // \ /// 4 5 // /// 6Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->right=newNode(4);root->right->left=newNode(5);root->right->left->left=newNode(6);vector<int>ans=noSibling(root);printList(ans);return0;}
Java
// Java Program to find nodes with no// siblings in a given binary treeimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{staticArrayList<Integer>noSibling(Nodenode){if(node==null)returnnewArrayList<>(Arrays.asList(-1));// create an empty result arrayArrayList<Integer>ans=newArrayList<>();Queue<Node>q=newLinkedList<>();q.add(node);while(!q.isEmpty()){Nodecurr=q.poll();// If this is an internal node, push the left// and right nodes into queueif(curr.left!=null&&curr.right!=null){q.add(curr.left);q.add(curr.right);}// If left child is NULL and right is not, // append right node into result and push// it into queue.elseif(curr.right!=null){ans.add(curr.right.data);q.add(curr.right);}// If right child is NULL and left is // not, append left child to result// and push left node into queue.elseif(curr.left!=null){ans.add(curr.left.data);q.add(curr.left);}}// if there are 0 nodes// without any siblingsif(ans.isEmpty())ans.add(-1);// else sort the resultelseCollections.sort(ans);returnans;}staticvoidprintList(ArrayList<Integer>v){for(inti:v){System.out.print(i+" ");}System.out.println();}publicstaticvoidmain(String[]args){// Create a hard coded binary tree// 1// / \// 2 3// \ /// 4 5// /// 6Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.right=newNode(4);root.right.left=newNode(5);root.right.left.left=newNode(6);ArrayList<Integer>ans=noSibling(root);printList(ans);}}
Python
# Python Program to find nodes with no# siblings in a given binary treefromqueueimportQueueclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=NonedefnoSibling(node):ifnotnode:return[-1]# create an empty result arrayans=[]q=Queue()q.put(node)whilenotq.empty():curr=q.get()# If this is an internal node, push the left# and right nodes into queueifcurr.leftandcurr.right:q.put(curr.left)q.put(curr.right)# If left child is NULL and right is not, # append right node into result and push# it into queue.elifcurr.right:ans.append(curr.right.data)q.put(curr.right)# If right child is NULL and left is # not, append left child to result# and push left node into queue.elifcurr.left:ans.append(curr.left.data)q.put(curr.left)# if there are 0 nodes# without any siblingsifnotans:ans.append(-1)# else sort the resultelse:ans.sort()returnansdefprintList(v):print(" ".join(map(str,v)))if__name__=="__main__":# Create a hard coded binary tree# 1# / \# 2 3# \ /# 4 5# /# 6root=Node(1)root.left=Node(2)root.right=Node(3)root.left.right=Node(4)root.right.left=Node(5)root.right.left.left=Node(6)ans=noSibling(root)printList(ans)
C#
// C# Program to find nodes with no// siblings in a given binary treeusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{staticList<int>NoSibling(Nodenode){if(node==null)returnnewList<int>{-1};// create an empty result arrayList<int>ans=newList<int>();Queue<Node>q=newQueue<Node>();q.Enqueue(node);while(q.Count>0){Nodecurr=q.Dequeue();// If this is an internal node, push the left// and right nodes into queueif(curr.left!=null&&curr.right!=null){q.Enqueue(curr.left);q.Enqueue(curr.right);}// If left child is NULL and right is not, // append right node into result and push// it into queue.elseif(curr.right!=null){ans.Add(curr.right.data);q.Enqueue(curr.right);}// If right child is NULL and left is // not, append left child to result// and push left node into queue.elseif(curr.left!=null){ans.Add(curr.left.data);q.Enqueue(curr.left);}}// if there are 0 nodes// without any siblingsif(ans.Count==0)ans.Add(-1);// else sort the resultelseans.Sort();returnans;}staticvoidPrintList(List<int>v){foreach(intiinv){Console.Write(i+" ");}Console.WriteLine();}staticvoidMain(string[]args){// Create a hard coded binary tree// 1// / \// 2 3// \ /// 4 5// /// 6Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.right=newNode(4);root.right.left=newNode(5);root.right.left.left=newNode(6);List<int>ans=NoSibling(root);PrintList(ans);}}
JavaScript
// JavaScript Program to find nodes with no// siblings in a given binary treeclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}functionnoSibling(node){if(node===null)return[-1];// create an empty result arrayconstans=[];constq=[];q.push(node);while(q.length>0){letcurr=q.shift();// If this is an internal node, push the left// and right nodes into queueif(curr.left!==null&&curr.right!==null){q.push(curr.left);q.push(curr.right);}// If left child is NULL and right is not, // append right node into result and push// it into queue.elseif(curr.right!==null){ans.push(curr.right.data);q.push(curr.right);}// If right child is NULL and left is // not, append left child to result// and push left node into queue.elseif(curr.left!==null){ans.push(curr.left.data);q.push(curr.left);}}// if there are 0 nodes// without any siblingsif(ans.length===0)ans.push(-1);// else sort the resultelseans.sort((a,b)=>a-b);returnans;}functionprintList(v){console.log(v.join(" "));}// Create a hard coded binary tree// 1// / \// 2 3// \ /// 4 5// /// 6constroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.right=newNode(4);root.right.left=newNode(5);root.right.left.left=newNode(6);constans=noSibling(root);printList(ans);
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.