-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserializationLevel.java
More file actions
75 lines (62 loc) · 1.65 KB
/
Copy pathserializationLevel.java
File metadata and controls
75 lines (62 loc) · 1.65 KB
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
import java.util.*;
public class serializationLevel
{
static class Node
{
int data;
Node left;
Node right;
public Node()
{}
public Node(int val)
{
data=val;
left=null;
right=null;
}
}
public static void main(String args[])
{
System.out.println("Inside Main");
Node root= new Node(1);
root.left=new Node(2);
root.right=new Node(3);
root.left.left=new Node(0);
root.left.right=new Node(0);
root.right.left=new Node(4);
root.right.right=new Node(5);
System.out.println("Tree Created");
String s=serialize(root);
System.out.println("After Serialization: "+ s);
}
Node root;
public static String serialize(Node root)
{
StringBuilder sb=new StringBuilder();
if(root==null)
{
sb.append("X,");
}
System.out.println("Root= "+root.data);
//StringBuilder sb=new StringBuilder();
Queue<Node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty())
{
Node firstelement=q.poll();
sb.append(firstelement.data+",");
if(firstelement.left!=null)
{
//sb.append(","+firstelement.left.data);
q.add(firstelement.left);
}
if(firstelement.right!=null)
{
//sb.append(","+firstelement.right.data);
q.add(firstelement.right);
}
}
//System.out.println(sb);
return sb.toString();
}
}