判断一棵二叉树是否是平衡二叉树
public class e04IsBalancedTree {
public static class Node {
public int value;
public Node left;
public Node right;
public Node ( int value) {
this . value = value;
}
}
public static int process ( Node head) {
if ( head== null) {
return 0 ;
}
int leftData= process ( head. left) ;
int rightData= process ( head. right) ;
while ( leftData!= - 1 && rightData!= - 1 ) {
return Math. abs ( leftData- rightData) > 1 ? - 1 : Math. max ( leftData, rightData) + 1 ;
}
return - 1 ;
}
public static Boolean isB ( Node head) {
return process ( head) != - 1 ;
}
public static void main ( String[ ] args) {
Node A= new Node ( 1 ) ;
Node B= new Node ( 2 ) ;
Node C= new Node ( 3 ) ;
Node D= new Node ( 4 ) ;
Node E= new Node ( 5 ) ;
A. left= B;
B. left= C;
A. right= D;
C. left= E;
System. out. println ( isB ( A) ) ;
}
}