Skip to content

Commit e76e577

Browse files
author
Tushar Borole
committed
297. Serialize and Deserialize Binary Tree
1 parent 0720d92 commit e76e577

File tree

3 files changed

+70
-12
lines changed

3 files changed

+70
-12
lines changed

.idea/workspace.xml

Lines changed: 15 additions & 12 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@
9595
| 36 | [Valid Sudoku](https://leetcode.com/problems/valid-sudoku/) | [Itterative](valid_sudoku.js) | 68 ms | 37.7 MB | Medium | O(1) | O(1) | [:link:](https://leetcode.com/problems/valid-sudoku/solution/) |
9696
| 146 | [ LRU Cache](https://leetcode.com/problems/lru-cache/) | [Map](lru_cache.js) | 216 ms | 58.8 MB | Medium | O(1) | O(1) | |
9797
| 340 | [Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/) | [Sliding Window Approach](k_distinct_characters.js) | 68 ms | 37.1 MB | Hard | NlogN | | [:link:](https://www.youtube.com/watch?v=MK-NZ4hN7rs&t=1936s) |
98+
| 297 | [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) | [DFS Recursion](serialize_and_deserialize_binary_tree.js) | 80 ms | 43.6 MB | Hard | | | [:link:](https://www.youtube.com/watch?v=suj1ro8TIVY) |
9899

99100
## Others
100101

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// https://www.youtube.com/watch?v=YGZuDSs8fQo
2+
3+
function TreeNode(val) {
4+
this.val = val;
5+
this.left = this.right = null;
6+
}
7+
8+
/**
9+
* Encodes a tree to a single string.
10+
*
11+
* @param {TreeNode} root
12+
* @return {string}
13+
*/
14+
var serialize = function(root) {
15+
if (root === null) {
16+
return "null,";
17+
}
18+
let leftString = serialize(root.left);
19+
let rightString = serialize(root.right);
20+
return root.val + "," + leftString + rightString;
21+
serialize(root);
22+
};
23+
24+
/**
25+
* Decodes your encoded data to tree.
26+
*
27+
* @param {string} data
28+
* @return {TreeNode}
29+
*/
30+
var deserialize = function(data) {
31+
const list = data.split(",");
32+
let recur = function(list) {
33+
let val = list.shift();
34+
if (val === "null") return null;
35+
let newNode = new TreeNode(parseInt(val));
36+
newNode.left = recur(list);
37+
newNode.right = recur(list);
38+
return newNode;
39+
};
40+
return recur(list);
41+
};
42+
43+
/**
44+
* Your functions will be called as such:
45+
* deserialize(serialize(root));
46+
*/
47+
48+
let root = new TreeNode(1);
49+
root.left = new TreeNode(2);
50+
root.right = new TreeNode(3);
51+
root.right.left = new TreeNode(4);
52+
root.right.right = new TreeNode(5);
53+
54+
deserialize(serialize(root)); //?

0 commit comments

Comments
 (0)