欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

判断一棵二叉树是否是平衡二叉树

程序员文章站 2022-05-16 14:56:16
...

判断一棵二叉树是否是平衡二叉树

public class IsBalancedTree {
	public static class Node {
		public int value;
		public Node left;
		public Node right;

		public Node(int value) {
			this.value = value;
		}
	}

	public static boolean isBalance(Node head) {
		boolean[] b = new boolean[1];
		b[0] = true;
		getHeight(head, 1, b);
		return b[0];
	}

	public static int getHeight(Node head, int level, boolean[] b) {
		if (head == null) {
			return level;
		}
		int lH = getHeight(head.left, level + 1, b);
		if (!b[0]) {
			return level;
		}
		int rH = getHeight(head.right, level + 1, b);
		if (!b[0]) {
			return level;
		}
		if (Math.abs(lH - rH) > 1) {
			b[0] = false;
		}
		return Math.max(lH, rH);
	}