File tree Expand file tree Collapse file tree 2 files changed +56
-0
lines changed Expand file tree Collapse file tree 2 files changed +56
-0
lines changed Original file line number Diff line number Diff line change 1+ function isBalanced ( root ) {
2+ // find tree's leaves' levels
3+ const leavesDepths = getLeavesDepths ( root ) . sort ( ) ;
4+
5+ // TODO: check for empty trees, and that has less than 2 leaves
6+
7+ // if any leave depth is bigger than 2 than any other, then is not balanced
8+ return leavesDepths [ leavesDepths . length - 1 ] - leavesDepths [ leavesDepths . length - 2 ] < 2 ;
9+ }
10+
11+ function getLeavesDepths ( node , level = 0 , leavesDepths = [ ] ) {
12+ if ( ! node . adjacents . length ) {
13+ leavesDepths . push ( level ) ;
14+ }
15+
16+ node . adjacents . forEach ( function ( adj ) {
17+ getLeavesDepths ( adj , level + 1 , leavesDepths ) ;
18+ } ) ;
19+
20+ return leavesDepths ;
21+ }
22+
23+ module . exports = isBalanced ;
Original file line number Diff line number Diff line change 1+ const expect = require ( 'chai' ) . expect ;
2+ const Node = require ( './graph' ) . Node ;
3+ const Graph = require ( './graph' ) . Graph ;
4+ const isBalanced = require ( './is-balanced' ) ;
5+
6+ describe ( 'Graph: is balanced ?' , function ( ) {
7+ let graph ;
8+
9+ beforeEach ( function ( ) {
10+ graph = new Graph ( ) ;
11+ } ) ;
12+
13+ it ( 'should return true when is balanced and complete' , function ( ) {
14+ graph . add ( 0 , 1 ) ;
15+ const root = graph . add ( 0 , 2 ) ;
16+ expect ( isBalanced ( root ) ) . to . equal ( true ) ;
17+ } ) ;
18+
19+ it ( 'should return true when is balanced and not complete' , function ( ) {
20+ const root = graph . add ( 0 , 1 ) ;
21+ graph . add ( 0 , 2 ) ;
22+ graph . add ( 2 , 3 ) ;
23+ expect ( isBalanced ( root ) ) . to . equal ( true ) ;
24+ } ) ;
25+
26+ it ( 'should return false when is not balanced' , function ( ) {
27+ const root = graph . add ( 0 , 1 ) ;
28+ graph . add ( 0 , 2 ) ;
29+ graph . add ( 2 , 3 ) ;
30+ graph . add ( 3 , 4 ) ;
31+ expect ( isBalanced ( root ) ) . to . equal ( false ) ;
32+ } ) ;
33+ } ) ;
You can’t perform that action at this time.
0 commit comments