Skip to content

Commit d6c4f79

Browse files
authored
Create Nodes without sibling
1 parent f165d99 commit d6c4f79

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
/*
2+
For a given Binary Tree of type integer, print all the nodes without any siblings.
3+
4+
Input Format:
5+
The first and the only line of input will contain the node data, all separated by a single space.
6+
Since -1 is used as an indication whether the left or right node data exist for root, it will not be a part of the node data.
7+
8+
Output Format:
9+
The only line of output prints the node data in a top to down fashion with reference to the root.
10+
Node data in the left subtree will be printed first and then the right subtree.
11+
A single space will separate them all.
12+
13+
Constraints:
14+
1 <= N <= 10^5
15+
Where N is the total number of nodes in the binary tree.
16+
Time Limit: 1 second
17+
18+
Sample Input 1:
19+
5 6 10 2 3 -1 -1 -1 -1 -1 9 -1 -1
20+
Sample Output 1:
21+
9
22+
23+
Sample Input 2:
24+
2 4 5 6 -1 -1 7 20 30 80 90 -1 8 9 -1 -1 -1 -1 -1 -1 -1 -1 -1
25+
Sample Output 2:
26+
6 8 7 9
27+
28+
Explanation of Sample Input 2:
29+
In respect to the root, node data in the left subtree that satisfy the condition of not having a sibling would be 6 and 8, taken in a top-down sequence.
30+
Similarly, for the right subtree, 7 and 9 are the node data without any sibling.
31+
Since we print the siblings in the left-subtree first and then the siblings from the right subtree, taken in a top-down fashion, we print 6 8 7 9.
32+
*/
33+
/*
34+
35+
Following is the structure used to represent the Binary Tree Node
36+
37+
class BinaryTreeNode<T> {
38+
T data;
39+
BinaryTreeNode<T> left;
40+
BinaryTreeNode<T> right;
41+
42+
public BinaryTreeNode(T data) {
43+
this.data = data;
44+
this.left = null;
45+
this.right = null;
46+
}
47+
}
48+
49+
*/
50+
51+
public class Solution {
52+
53+
public static void printNodesWithoutSibling(BinaryTreeNode<Integer> root) {
54+
//Your code goes here
55+
if (root==null)
56+
{
57+
return;
58+
}
59+
60+
if (root.left==null && root.right==null)
61+
{
62+
return;
63+
}
64+
65+
if (root.left==null)
66+
{
67+
System.out.print(root.right.data+" ");
68+
printNodesWithoutSibling(root.right);
69+
}
70+
else if (root.right==null)
71+
{
72+
System.out.print(root.left.data+" ");
73+
printNodesWithoutSibling(root.left);
74+
75+
}
76+
else
77+
{
78+
printNodesWithoutSibling(root.left);
79+
printNodesWithoutSibling(root.right);
80+
}
81+
}
82+
83+
}

0 commit comments

Comments
 (0)