您的位置:首页 > 其它

【leetcode】Balanced Binary Tree

2014-07-29 22:46 302 查看
题目:

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

分析:该题要判断一棵二叉树是高度平衡的,平衡的条件是”对于任何一个节点,它的左右子树高度直插不超过1"。解法很显然是递归地判断每个节点是否满足高度平衡的要求,对于某个节点是否满足高度平衡,与三个因素有关:它的左子树是否高度平衡,它的右子树是否高度平衡,它的左右子树高度之差是否小于等于1。因此在递归的过程要传入两个参数:ifBalanced,该节点是否高度平衡,height,该节点的高度,可以定义内部类Node,包含以上变量。注意对于null节点,ifBalanced=true。

Java AC代码如下:

public boolean isBalanced(TreeNode root) {
		return cal(root).ifBalanced;
	}

	public Node cal(TreeNode root) {
		Node node = new Node();
		if (root == null) {
			node.height = 0;
			node.ifBalanced = true;
			return node;
		}
		node.left = cal(root.left);
		node.right = cal(root.right);
		node.height = Math.max(node.left.height, node.right.height) + 1;
		node.ifBalanced = (Math.abs(node.left.height - node.right.height) <= 1)
				&& node.left.ifBalanced && node.right.ifBalanced;
		return node;
	}

	class Node {
		boolean ifBalanced;
		int height;
		Node left;
		Node right;
	}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: