给定一棵二叉树的头节点,判断是不是平衡二叉树


/**
* 给定一棵二叉树的头节点,判断是不是平衡二叉树
*/
public class IsBalancedBT {

public static boolean isBalancedBT(Node root) {
if (root == null) {
return true;
}
return process(root).isBalanced;
}

private static ResultInfo process(Node node) {
if (node == null) {
return new ResultInfo(0, true);
}
ResultInfo leftResult = process(node.left);
ResultInfo rightResult = process(node.right);
int height = Math.max(leftResult.height, rightResult.height) + 1;
boolean isBalanced = true;
if (!leftResult.isBalanced || !rightResult.isBalanced || Math.abs(leftResult.height - rightResult.height) > 1) {
isBalanced = false;
}
return new ResultInfo(height, isBalanced);
}

/**
* 向左右子树索要信息
*/
public static class ResultInfo {

// 当前高度
public int height;

// 是否平衡
public boolean isBalanced;

public ResultInfo(int height, boolean isBalanced) {
this.height = height;
this.isBalanced = isBalanced;
}

}

/**
* 二叉树结构
*/
public static class Node {

public Node left;

public Node right;

}

}

/* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
原文地址:https://www.cnblogs.com/laydown/p/12952948.html