File tree Expand file tree Collapse file tree 1 file changed +23
-1
lines changed Expand file tree Collapse file tree 1 file changed +23
-1
lines changed Original file line number Diff line number Diff line change @@ -64,6 +64,28 @@ def is_balanced_v1(node):
6464    return  find_max_depth (node ) -  find_min_depth (node ) <  2 
6565
6666
67+ # Alternative Recursive Approach 
68+ def  _find_height (root ):
69+     if  root  is  None :
70+         return  0 
71+     left_height  =  _find_height (root .left )
72+     if  left_height  ==  - 1 :
73+         return  - 1 
74+ 
75+     right_height  =  _find_height (root .right )
76+     if  right_height  ==  - 1 :
77+         return  - 1 
78+ 
79+     if  abs (left_height  -  right_height ) >  1 :
80+         return  - 1 
81+ 
82+     return  max (left_height , right_height ) +  1 
83+ 
84+ 
85+ def  is_balanced_v3 (root ):
86+     return  _find_height (root ) >  - 1 
87+ 
88+ 
6789def  _gen_balanced_1 ():
6890    root  =  BinaryNode (1 )
6991    root .left  =  BinaryNode (2 )
@@ -118,7 +140,7 @@ def _gen_unbalanced_2():
118140    (_gen_unbalanced_2 , False ),
119141]
120142
121- testable_functions  =  [is_balanced_v1 , is_balanced_v2 ]
143+ testable_functions  =  [is_balanced_v1 , is_balanced_v2 ,  is_balanced_v3 ]
122144
123145
124146def  test_is_balanced ():
    
 
   
 
     
   
   
          
     
  
    
     
 
    
      
     
 
     
    You can’t perform that action at this time.
  
 
    
  
     
    
      
        
     
 
       
      
     
   
 
    
    
  
 
  
 
     
    
0 commit comments