@@ -22,48 +22,28 @@ const utils = {
2222 }
2323 } ,
2424
25- preorder ( root ) {
26- /** returning an array so as to make testing easy */
27- let arr = [ ] ;
28- if ( root === null ) return [ ] ;
29- arr . push ( root . value ) ;
30- 31- const left = this . preorder ( root . leftChild ) ;
32- arr = [ ...arr , ...left ] ;
33- 34- const right = this . preorder ( root . rightChild ) ;
35- arr = [ ...arr , ...right ] ;
36- return arr ;
25+ preorder ( root , array ) {
26+ if ( root === null ) return array ;
27+ array . push ( root . value ) ;
28+ this . preorder ( root . leftChild , array ) ;
29+ this . preorder ( root . rightChild , array ) ;
30+ return array ;
3731 } ,
3832
39- inorder ( root ) {
40- /** left - root - right */
41- if ( root === null ) return [ ] ;
42- let arr = [ ] ;
43- const left = this . inorder ( root . leftChild ) ;
44- arr = [ ...left , ...arr ] ;
45- 46- // print root
47- arr = [ ...arr , root . value ] ;
48- 49- const right = this . inorder ( root . rightChild ) ;
50- arr = [ ...arr , ...right ] ;
51- return arr ;
33+ inorder ( root , array ) {
34+ if ( root === null ) return array ;
35+ this . inorder ( root . leftChild , array ) ;
36+ array . push ( root . value ) ;
37+ this . inorder ( root . rightChild , array ) ;
38+ return array ;
5239 } ,
5340
54- postorder ( root ) {
55- /** left - right - root */
56- 57- if ( root === null ) return [ ] ;
58- let arr = [ ] ;
59- 60- const left = this . postorder ( root . leftChild ) ;
61- arr = [ ...left , ...arr ] ;
62- 63- const right = this . postorder ( root . rightChild ) ;
64- arr = [ ...arr , ...right ] ;
65- 66- return [ ...arr , root . value ] ;
41+ postorder ( root , array ) {
42+ if ( root === null ) return array ;
43+ this . postorder ( root . leftChild , array ) ;
44+ this . postorder ( root . rightChild , array ) ;
45+ array . push ( root . value ) ;
46+ return array ;
6747 } ,
6848
6949 // eslint-disable-next-line consistent-return
0 commit comments