判断一棵树是否为平衡二叉树
作者:互联网
1、判断左树是否平衡,并返回左树高度
2、判断右树是否平衡,并返回右树高度
3、判断左右树高度差是否大于1,如果大于1,则不是平衡二叉树
public class TreeNode {
public static class Node {
private String number;
private Node left;
private Node right;
public Node(String number, Node leftNode, Node rightNode) {
this.number = number;
this.left = leftNode;
this.right = rightNode;
}
}
public static void creadNodeNode() {
Node Node7 = new Node("7", null, null);
Node Node6 = new Node("6", null, null);
Node Node5 = new Node("5", null, null);
Node Node4 = new Node("4", null, null);
Node Node3 = new Node("3", Node6, Node7);
Node Node2 = new Node("2", Node4, Node5);
Node Node1 = new Node("1", Node2, Node3);
priIsB(Node1);
}
public static void priIsB(Node node) {
boolean isB = getIsB(node).isB;
System.out.println(isB);
}
/**
* leave: 遍历到那一层
*
* @param node
* @return
*/
public static ReturnDate getIsB(Node node) {
if (null == node) {
return new ReturnDate(true, 0);
}
ReturnDate left = getIsB(node.left);
if (!left.isB) {
return new ReturnDate(false, 0);
}
ReturnDate right = getIsB(node.right);
if (!right.isB) {
return new ReturnDate(false, 0);
}
if (Math.abs(left.leave - right.leave) > 1) {
return new ReturnDate(false, 0);
}
return new ReturnDate(true, Math.max(left.leave, right.leave) + 1);
}
public static void main(String[] args) {
creadNodeNode();
}
}
/**
*
* 返回的是否平衡信息及高度
*
*/
class ReturnDate {
boolean isB;
int leave;
public ReturnDate(boolean is, int leave) {
this.isB = isB;
this.leave = leave;
}
}
标签:Node,ReturnDate,一棵树,leave,二叉树,isB,new,平衡,null 来源: https://blog.csdn.net/qq_41597666/article/details/122135383