Skip to content

Commit ae0cdbf

Browse files
authored
Create Binary Trees2-Create & Insert Duplicate Node
1 parent 4c2fa54 commit ae0cdbf

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
For a given a Binary Tree of type integer, duplicate every node of the tree and attach it to the left of itself.
2+
The root will remain the same. So you just need to insert nodes in the given Binary Tree.
3+
Example:
4+
alt txt
5+
6+
After making the changes to the above-depicted tree, the updated tree will look like this.
7+
alt txt
8+
9+
You can see that every node in the input tree has been duplicated and inserted to the left of itself.
10+
Input format :
11+
The first and the only line of input will contain the node data, all separated by a single space. 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.
12+
Output Format :
13+
The updated tree will be printed in a level order fashion where each level will be printed on a new line.
14+
Elements on every level will be printed in a linear fashion. A single space will separate them.
15+
Note:
16+
You are not required to print anything explicitly. It has already been taken care of. Just implement the function to achieve the desired structure of the tree.
17+
Constraints :
18+
1 <= N <= 10^5
19+
Where N is the total number of nodes in the binary tree.
20+
21+
Time Limit: 1 sec
22+
Sample Input 1:
23+
10 20 30 40 50 -1 60 -1 -1 -1 -1 -1 -1
24+
Sample Output 1:
25+
10
26+
10 30
27+
20 30 60
28+
20 50 60
29+
40 50
30+
40
31+
Sample Input 2:
32+
8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1
33+
Sample Output 2:
34+
8
35+
8 10
36+
5 10
37+
5 6
38+
2 6 7
39+
2 7
40+
41+
*************************************Solution****************************************
42+
43+
public static void insertDuplicateNode(BinaryTreeNode<Integer> root) {
44+
45+
if(root==null)
46+
return;
47+
BinaryTreeNode<Integer> duplicate=new BinaryTreeNode<Integer>(root.data);
48+
BinaryTreeNode<Integer> temp=root.left;
49+
root.left=duplicate;
50+
duplicate.left=temp;
51+
insertDuplicateNode(root.left.left);
52+
insertDuplicateNode(root.right);
53+
54+
}

0 commit comments

Comments
 (0)