@@ -7,39 +7,25 @@ class Node {
7
7
}
8
8
function levelOrderTraversalWithDirection ( root ) {
9
9
if ( root == null ) return ;
10
- let stack = [ ] ;
11
- stack . push ( root ) ;
12
- let queue = [ ] ;
13
- let leftToRight = true ;
14
- while ( stack . length != 0 ) {
10
+ let stack1 = [ root ] ;
11
+ let stack2 = [ ] ;
12
+ while ( stack1 . length != 0 || stack2 . length != 0 ) {
15
13
let levelElements = '' ;
16
- while ( stack . length != 0 ) {
17
- let temp = stack . pop ( ) ;
18
- if ( leftToRight ) {
19
- if ( temp . leftNode ) queue . push ( temp . leftNode ) ;
20
- if ( temp . rightNode ) queue . push ( temp . rightNode ) ;
21
- } else {
22
- if ( temp . rightNode ) queue . push ( temp . rightNode ) ;
23
- if ( temp . leftNode ) queue . push ( temp . leftNode ) ;
24
- }
14
+ while ( stack1 . length != 0 ) {
15
+ let temp = stack1 . pop ( ) ;
16
+ if ( temp . rightNode ) stack2 . push ( temp . rightNode ) ;
17
+ if ( temp . leftNode ) stack2 . push ( temp . leftNode ) ;
25
18
levelElements = levelElements + temp . data + ' ' ;
26
19
}
27
20
console . log ( levelElements ) ;
28
21
levelElements = '' ;
29
- while ( queue . length != 0 ) {
30
- let temp = queue . shift ( ) ;
31
- if ( leftToRight ) {
32
- if ( temp . leftNode ) stack . push ( temp . leftNode ) ;
33
- if ( temp . rightNode ) stack . push ( temp . rightNode ) ;
34
- } else {
35
- if ( temp . rightNode ) stack . push ( temp . rightNode ) ;
36
- if ( temp . leftNode ) stack . push ( temp . leftNode ) ;
37
- }
22
+ while ( stack2 . length != 0 ) {
23
+ let temp = stack2 . pop ( ) ;
24
+ if ( temp . leftNode ) stack1 . push ( temp . leftNode ) ;
25
+ if ( temp . rightNode ) stack1 . push ( temp . rightNode ) ;
38
26
levelElements = levelElements + temp . data + ' ' ;
39
27
}
40
28
console . log ( levelElements ) ;
41
- if ( leftToRight ) leftToRight = false ;
42
- else leftToRight = true ;
43
29
}
44
30
}
45
31
//level - 1
0 commit comments