《Career Cup Top 150 Questions》第四章第一题

附上原题:

Implement a function to check if a tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one.


书上原题的解法:

public static int maxDepth(TreeNode root) {
	if (root == null) {
		return 0;
	}
	return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}

public static int minDepth(TreeNode root) {
	if (root == null) {
		return 0;
	}
	return 1 + Math.min(minDepth(root.left), minDepth(root.right));
}

public static boolean isBalanced(TreeNode root){
	return (maxDepth(root) - minDepth(root) <= 1);
}

书上这段代码是有问题的,只判断了左右子树的深度差,却没有判断左右子树本身是不是平衡二叉树,代码应该为:

public static boolean isBalanced(TreeNode root){
	return (isBalanced(root.left) && isBalanced(root.right) && maxDepth(root) - minDepth(root) <= 1);
}

但是这样也有问题,在判断左子树(右子树)是不是平衡二叉树的时候遍历了所有左(右)子节点,在maxDepth()又遍历了一遍,每一个叶子节点遍历了logn次,整体复杂度为O(n*logn)。

下面这段代码每个结点都只遍历一次,整体复杂度为O(n):

struct Data
{
	bool isBalance;
	int height;
};

Data isBalanced(TreeNode root){
	Data value;
	if(NULL == root)
	{
		value.isBalance = true;
		value.height = 0;
	}
	else
	{
		Data left = isBalanced(root.left);
		Data right = isBalanced(root.right);
		value.isBalance = left.isBalance && right.isBalance && abs(left.height - right.height) <= 1;
		value.height = max(left.height, right.height) + 1;
	}
	return value;
}

P.S.  函数名字isBalanced有点不太好,Don't mind this...


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值