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 1616var flatten = function ( root ) {
1717 var stack = [ ] ;
1818 var p = root ;
19-
19+
2020 while ( p !== null || stack . length !== 0 ) {
2121 if ( p . right !== null ) {
2222 stack . push ( p . right ) ;
2323 }
24-
24+
2525 if ( p . left !== null ) { // [!!!]point of confusing, if null then pop stack
2626 p . right = p . left ;
2727 p . left = null ;
2828 } else if ( stack . length !== 0 ) {
2929 var node = stack . pop ( ) ;
3030 p . right = node ;
3131 }
32-
32+
3333 p = p . right ;
3434 }
3535} ;
3636
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