File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed
serialize-and-deserialize-binary-tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for a binary tree node.
3+ * function TreeNode(val) {
4+ * this.val = val;
5+ * this.left = this.right = null;
6+ * }
7+ */
8+
9+ const NULL_SIGN = 'X' ;
10+
11+ /**
12+ * Encodes a tree to a single string.
13+ * 시간복잡도: O(n)
14+ * 공간복잡도: O(h) (h: 재귀 스택 깊이 즉 트리 높이)
15+ * @param {TreeNode } root
16+ * @return {string }
17+ */
18+ const serialize = function ( root ) {
19+ const result = [ ] ;
20+
21+ function traverse ( root ) {
22+ result . push ( root ?. val ?? NULL_SIGN ) ;
23+ if ( ! root ) {
24+ return ;
25+ }
26+ traverse ( root . left ) ;
27+ traverse ( root . right ) ;
28+ }
29+
30+ traverse ( root ) ;
31+ return result . join ( ',' ) ;
32+ } ;
33+
34+ /**
35+ * Decodes your encoded data to tree.
36+ * 시간복잡도: O(n)
37+ * 공간복잡도: O(h) (h: 재귀 스택 깊이 즉 트리 높이)
38+ * @param {string } data
39+ * @return {TreeNode }
40+ */
41+ const deserialize = function ( data ) {
42+ const splited = data . split ( ',' ) ;
43+ let i = 0 ;
44+
45+ function makeTree ( ) {
46+ if ( splited [ i ] === NULL_SIGN ) {
47+ return null ;
48+ }
49+
50+ const node = new TreeNode ( Number ( splited [ i ] ) ) ;
51+ i += 1 ;
52+ node . left = makeTree ( ) ;
53+ i += 1 ;
54+ node . right = makeTree ( ) ;
55+
56+ return node ;
57+ }
58+
59+ return makeTree ( ) ;
60+ } ;
61+
62+ /**
63+ * Your functions will be called as such:
64+ * deserialize(serialize(root));
65+ */
You can’t perform that action at this time.
0 commit comments