public class IsBalancedTree55 {
static class Node {
int val;
Node left;
Node right;
public Node(int val) {
this.val = val;
}
@Override
public String toString() {
return "Node{" +
"val=" + val +
", left=" + left +
", right=" + right +
'}';
}
}
public static void main(String[] args) {
Node root = new Node(8);
Node node21 = new Node(6);
Node node22 = new Node(10);
Node node31 = new Node(5);
Node node32 = new Node(7);
Node node33 = new Node(9);
Node node34 = new Node(11);
root.left = node21;
root.right = node22;
node21.left = node31;
node21.right = node32;
node22.left = node33;
node22.right = node34;
System.out.println(isBalanced(root));
}
private static boolean isBalanced(Node root) {
if (root == null)
return true;
//root左孩子的树高
int leftHeight = height(root.left);
//root右孩子的树高
int rightHeight = height(root.right);
//root左右孩子高度差大于1,返回false
if (Math.abs(rightHeight - leftHeight) > 1) {
return false;
}
return isBalanced(root.left) && isBalanced(root.right);
}
private static int height(Node root) {
if (root == null)
return 0;
int left = height(root.left);
int right = height(root.right);
return Math.max(left, right) + 1;
}
}
来源:https://blog.csdn.net/weixin_43065507/article/details/99330661