-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Trees2-Print Levelwise
86 lines (77 loc) · 2.25 KB
/
Binary Trees2-Print Levelwise
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
For a given a Binary Tree of type integer, print the complete information of every node, when traversed in a level-order fashion.
To print the information of a node with data D, you need to follow the exact format :
D:L:X,R:Y
Where D is the data of a node present in the binary tree.
X and Y are the values of the left(L) and right(R) child of the node.
Print -1 if the child doesn't exist.
Example:
alt text
For the above depicted Binary Tree, the level order travel will be printed as followed:
1:L:2,R:3
2:L:4,R:-1
3:L:5,R:6
4:L:-1,R:7
5:L:-1,R:-1
6:L:-1,R:-1
7:L:-1,R:-1
Note: There is no space in between while printing the information for each node.
Input Format:
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.
Output Format:
Information of all the nodes in the Binary Tree will be printed on a different line where each node will follow a format of D:L:X,R:Y, without any spaces in between.
Constraints:
1 <= N <= 10^5
Where N is the total number of nodes in the binary tree.
Time Limit: 1 sec
Sample Input 1:
8 3 10 1 6 -1 14 -1 -1 4 7 13 -1 -1 -1 -1 -1 -1 -1
Sample Output 1:
8:L:3,R:10
3:L:1,R:6
10:L:-1,R:14
1:L:-1,R:-1
6:L:4,R:7
14:L:13,R:-1
4:L:-1,R:-1
7:L:-1,R:-1
13:L:-1,R:-1
Sample Input 2:
1 2 3 4 5 6 7 -1 -1 -1 -1 -1 -1 -1 -1
Sample Output 2:
1:L:2,R:3
2:L:4,R:5
3:L:6,R:7
4:L:-1,R:-1
5:L:-1,R:-1
6:L:-1,R:-1
7:L:-1,R:-1
****************************************************Code*******************************************
import java.util.*;
public static void printLevelWise(BinaryTreeNode<Integer> root) {
if(root==null)
return;
Queue<BinaryTreeNode<Integer>> node = new LinkedList<BinaryTreeNode<Integer>>();
node.add(root);
while(!node.isEmpty())
{
BinaryTreeNode<Integer> front= node.poll();
System.out.print(front.data+":");
if(front.left!=null)
{
node.add(front.left);
System.out.print("L:"+front.left.data);
}
else{
System.out.print("L:-1");
}
if(front.right!=null)
{
node.add(front.right);
System.out.print(",R:"+front.right.data);
}
else{
System.out.print(",R:-1");
}
System.out.println();
}
}