File tree 1 file changed +30
-29
lines changed
scripts/algorithms/S/Serialize and Deserialize Binary Tree
1 file changed +30
-29
lines changed Original file line number Diff line number Diff line change 1
- /**
2
- * Encodes a tree to a single string.
3
- *
4
- * @param {TreeNode } root
5
- * @return {string }
6
- */
7
- var serialize = function ( root ) {
8
- let result = [ ] ;
9
- const dfs = ( r ) => {
10
- if ( ! r ) {
11
- result . push ( 'N' ) ;
12
- return ;
1
+ var serialize = function ( root ) {
2
+ if ( ! root ) return "" ;
3
+ let res = [ ] ;
4
+
5
+ function getNode ( node ) {
6
+ if ( ! node ) {
7
+ res . push ( "null" ) ;
8
+ } else {
9
+ res . push ( node . val ) ;
10
+ getNode ( node . left ) ;
11
+ getNode ( node . right ) ;
13
12
}
14
- result . push ( r . val ) ;
15
- dfs ( r . left ) ;
16
- dfs ( r . right ) ;
17
13
}
18
- dfs ( root ) ;
19
- return result . join ( "," )
14
+
15
+ getNode ( root ) ;
16
+
17
+ return res . join ( "," ) ;
20
18
} ;
21
19
22
20
/**
25
23
* @param {string } data
26
24
* @return {TreeNode }
27
25
*/
28
- var deserialize = function ( data ) {
29
- const vals = data . split ( "," ) ;
30
- const dfs = ( stream ) => {
31
- const item = stream . shift ( ) ;
32
- if ( item == 'N' ) {
33
- return null ;
34
- }
35
- const node = new TreeNode ( item ) ;
36
- node . left = dfs ( stream ) ;
37
- node . right = dfs ( stream ) ;
26
+ var deserialize = function ( data ) {
27
+ if ( data === "" ) return null ;
28
+ const arr = data . split ( "," ) ;
29
+
30
+ function buildTree ( array ) {
31
+ const nodeVal = array . shift ( ) ;
32
+
33
+ if ( nodeVal === "null" ) return null ;
34
+
35
+ const node = new TreeNode ( nodeVal ) ;
36
+ node . left = buildTree ( array ) ; //build left first
37
+ node . right = buildTree ( array ) ; //build right with updated array.
38
+
38
39
return node ;
39
- } ;
40
+ }
40
41
41
- return dfs ( vals ) ;
42
+ return buildTree ( arr ) ;
42
43
} ;
You can’t perform that action at this time.
0 commit comments