-
Notifications
You must be signed in to change notification settings - Fork 481
/
Copy path0297.js
38 lines (37 loc) · 828 Bytes
/
0297.js
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
/**
* Encodes a tree to a single string.
*
* @param {TreeNode} root
* @return {string}
*/
var serialize = function(root) {
let res = "";
let postOrder = function(root) {
if (root == null) {
res += "# "; return;
}
postOrder(root.left);
postOrder(root.right);
res += root.val + " ";
}
postOrder(root);
return res;
};
/**
* Decodes your encoded data to tree.
*
* @param {string} data
* @return {TreeNode}
*/
var deserialize = function(data) {
let datas = data.split(" "); datas.pop();
let deOrder = function() {
let val = datas.pop();
if (val == "#") return null;
let root = new TreeNode(Number(val));
root.right = deOrder();
root.left = deOrder();
return root;
}
return deOrder();
};