File tree Expand file tree Collapse file tree 1 file changed +26
-3
lines changed Expand file tree Collapse file tree 1 file changed +26
-3
lines changed Original file line number Diff line number Diff line change 16
16
var flatten = function ( root ) {
17
17
var stack = [ ] ;
18
18
var p = root ;
19
-
19
+
20
20
while ( p !== null || stack . length !== 0 ) {
21
21
if ( p . right !== null ) {
22
22
stack . push ( p . right ) ;
23
23
}
24
-
24
+
25
25
if ( p . left !== null ) { // [!!!]point of confusing, if null then pop stack
26
26
p . right = p . left ;
27
27
p . left = null ;
28
28
} else if ( stack . length !== 0 ) {
29
29
var node = stack . pop ( ) ;
30
30
p . right = node ;
31
31
}
32
-
32
+
33
33
p = p . right ;
34
34
}
35
35
} ;
36
36
37
+ // Recursive solution
38
+
39
+ var flatten = function ( root ) {
40
+ if ( root === null || ( root . left === null && root . right === null ) ) {
41
+ return ;
42
+ }
43
+
44
+ var rootLeft = root . left ;
45
+ var rootRight = root . right ;
46
+ root . left = null ;
47
+ root . right = null ;
48
+
49
+ flatten ( rootLeft ) ;
50
+ flatten ( rootRight ) ;
51
+
52
+ root . right = rootLeft ;
53
+
54
+ var aux = root ;
55
+ while ( aux !== null && aux . right !== null ) {
56
+ aux = aux . right ;
57
+ }
58
+ aux . right = rootRight ;
59
+ } ;
You can’t perform that action at this time.
0 commit comments