File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -24,3 +24,41 @@ const lcaDeepestLeaves = function(root) {
2424 return lcaDeepestLeaves ( root . right )
2525 }
2626}
27+
28+ // BFS
29+
30+ const lcaDeepestLeaves = function ( root ) {
31+ let current = [ root ] ;
32+ let level = 0 ;
33+ let last = [ ] ;
34+ while ( current . length ) {
35+ let next = [ ] ;
36+ for ( var i = 0 ; i < current . length ; i ++ ) {
37+ if ( current [ i ] . left ) {
38+ current [ i ] . left . parent = current [ i ] ;
39+ next . push ( current [ i ] . left ) ;
40+ }
41+ if ( current [ i ] . right ) {
42+ current [ i ] . right . parent = current [ i ] ;
43+ next . push ( current [ i ] . right ) ;
44+ }
45+ }
46+ last = current ;
47+ current = next ;
48+ }
49+ let parent = last [ 0 ] . parent ;
50+ if ( ! parent ) {
51+ return last [ 0 ] ;
52+ }
53+ while ( last . length > 1 ) {
54+ let next = [ ] ;
55+ for ( var i = 0 ; i < last . length ; i ++ ) {
56+ newParent = last [ i ] . parent ;
57+ if ( ! next . includes ( newParent ) ) {
58+ next . push ( newParent ) ;
59+ }
60+ }
61+ last = next ;
62+ }
63+ return last [ 0 ] ;
64+ } ;
You can’t perform that action at this time.
0 commit comments