左树是否平衡,如果左树不平衡,false
左树是否平衡,如果右树不平衡,false
左右都平衡,左树高度hl,右树高度hr
求出高度差|hl-hr|是否大于1
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int data) {
this.value = data;
}
}
public static class ReturnData{
public boolean isB;
public int height;
public ReturnData(boolean isB,int height){
this.isB=isB;
this.height=height;
}
}
public static ReturnData process(Node node){
if(node==null)
return new ReturnData(true, 0);
ReturnData leftData= process(node.left);
if(!leftData.isB){
return new ReturnData(false, 0);
}
ReturnData rightData = process(node.right);
if(!rightData.isB){
return new ReturnData(false, 0);
}
if(Math.abs(leftData.height-rightData.height)>1){
return new ReturnData( false, 0);
}
return new ReturnData(true, Math.max(leftData.height, rightData.height)+1);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Node head = new Node(1);
head.left = new Node(2);
head.right = new Node(3);
head.left.left = new Node(4);
head.left.right = new Node(5);
head.right.left = new Node(6);
System.out.println(process(head).isB);
}
递归最后会进入到最左下面的子树D,只有一个结点返回(true,0),然后来到E,返回(true,0)。此时左右两棵子树都是平衡的,返回较大子树的高度+1和true。即DBE这个子树是平衡的,B的高度是左右子树较大树高+1。然后执行到C,进入递归,左侧树返回(true,0),右侧返回(true,0)。C返回的是(true,2)。A的左右子树高度分别是2,2。也符合条件返回true。