Binary Tree: a binary tree to determine whether it is a balanced binary tree

If the tree each node is composed of a balanced binary tree, that is the whole balanced binary tree.
Specifically: left subtree is determined whether or not the balance, the balance is determined whether the right subtree, if the balance of all, that the height difference thereof is smaller than 1

public class BalanceTree {
	// 如果每个节点构成的树都是平衡二叉树,那整体就是平衡二叉树
	// 具体为:判断左子树是否平衡,判断右子树是否平衡,如果都平衡,那它们的高度差是否小于1
	public static class Node {
		public int value;
		public Node left;
		public Node right;
		public Node(int data) {
			this.value = data;
		}
	}
	public static boolean isBalance(Node head) {
		boolean[] res = new boolean[1];
		res[0] = true;
		getHeight(head, 1, res);
		return res[0];
	}
	public static int getHeight(Node head, int level, boolean[] res) {
		if (head == null) {
			return level;
		}
		int lH = getHeight(head.left, level + 1, res);// 左子树高度
		if (!res[0]) {
			return level;// 左子树不平衡,直接返回
		}
		int rH = getHeight(head.right, level + 1, res);// 右子树高度
		if (!res[0]) {
			return level;// 右子树不平衡,直接返回
		}
		if (Math.abs(lH - rH) > 1) {// 左、右子树高度差大于1
			res[0] = false; // 表示不平衡
		}
		return Math.max(lH, rH);// 返回左、右子树中高度较大的一个
	}
	public static void main(String[] args) {
		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);
		head.right.right = new Node(7);
		System.out.println(isBalance(head));
	}
}

Guess you like

Origin blog.csdn.net/qq_43165002/article/details/90750842