Cracking the coding interview--Q4.1

本文介绍了一个用于检查树是否平衡的算法。平衡树定义为任意两个叶子节点到根节点的距离之差不大于1。文中提供了实现该算法的具体代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

原文:

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.

译文:

实现一个函数去检查一个树是否是平衡,对于这个问题的目的,一个平衡的树是被定义为任意两个叶子结点到根结点的距离之差不大于1。

解答

首先要审清楚题目的“平衡”的意思,是指任意两个叶子到根结点距离之差不大于1,所以并不是要判断是否是平衡二叉树(空树或它的左右两个子树的高度差的绝对值不超过1),方法如下:

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);
	}

---EOF---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值