Skip to content

Commit bd096b2

Browse files
committed
Added serialize and deserialize binary tree problem
1 parent 5d6c3a1 commit bd096b2

File tree

2 files changed

+88
-76
lines changed

2 files changed

+88
-76
lines changed

Codechef Problems/MaximumArrayXOR.java

Lines changed: 0 additions & 76 deletions
This file was deleted.
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
/*
2+
Implementation of Serialize and Deserialize Binary Tree
3+
4+
According to the problem:
5+
We need to ensure that a binary tree can be serialized to a string and this string
6+
can be deserialized to the original tree structure.
7+
8+
NOTE:Serialization is the process of converting a data structure or object into a sequence of
9+
bits so that it can be stored in a file or memory buffer, or transmitted across a network
10+
connection link to be reconstructed later in the same or another computer environment.
11+
12+
Link to the problem: https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
13+
*/
14+
15+
/*
16+
Input: root = [1,2,3,null,null,4,5]
17+
Output: [1,2,3,null,null,4,5]
18+
*/
19+
/**
20+
* Definition for a binary tree node.
21+
* struct TreeNode {
22+
* int val;
23+
* TreeNode *left;
24+
* TreeNode *right;
25+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
26+
* };
27+
*/
28+
class Codec {
29+
TreeNode* makeTree(queue<string> &q) {
30+
string s = q.front();
31+
q.pop();
32+
if(s=="null")
33+
return NULL;
34+
TreeNode* root = new TreeNode(stoi(s));
35+
root->left = makeTree(q);
36+
root->right = makeTree(q);
37+
return root;
38+
}
39+
public:
40+
41+
// Encodes a tree to a single string.
42+
string serialize(TreeNode* root) {
43+
if(!root)
44+
return "null,";
45+
return to_string(root->val)+","+ serialize(root->left) + serialize(root->right);
46+
}
47+
48+
// Decodes your encoded data to tree.
49+
TreeNode* deserialize(string data) {
50+
string s ="";
51+
queue <string> q;
52+
for(char c: data) {
53+
if(c ==',') {
54+
q.push(s);
55+
s="";
56+
continue;
57+
}
58+
s+=c;
59+
}
60+
return makeTree(q);
61+
}
62+
}
63+
64+
/*
65+
Time complexity: O(n)
66+
67+
Test cases:
68+
69+
Example 1:
70+
71+
Input: root = [1,2,3,null,null,4,5]
72+
Output: [1,2,3,null,null,4,5]
73+
74+
Example 2:
75+
76+
Input: root = []
77+
Output: []
78+
79+
Example 3:
80+
81+
Input: root = [1]
82+
Output: [1]
83+
84+
Example 4:
85+
86+
Input: root = [1,2]
87+
Output: [1,2]
88+
*/

0 commit comments

Comments
 (0)