求一个二叉树中任意两个节点间的最大距离, 两个节点的距离的定义是这两个节点间边的个数,比如某个孩子节点和父节点间的距离是1,和相邻兄弟节点间的距离是2,优化时间空间复杂度。

本文介绍了一种求解二叉树中任意两节点间最大距离的方法,并提供了具体实现代码。通过递归计算左右子树的高度来确定以当前节点为根的最大距离。

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

网易有道笔试:
求一个二叉树中任意两个节点间的最大距离,
两个节点的距离的定义是这两个节点间边的个数,
比如某个孩子节点和父节点间的距离是1,
和相邻兄弟节点间的距离是2,
优化时间空间复杂度。

思路:
用l_depth和r_depth保存左子树最大高度和右子树最大高度。
res保存以该节点为根节点时的的最大距离,不断向上更新。

class TreeNode {
	int l_depth;
	int r_depth;
	int res;
	int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}
public class m23_maxDisTree {
	public static void main(String[] args) {
		int max=0;
		TreeNode root = new TreeNode(2);
		root.left=new TreeNode(3);
		root.left.left=new TreeNode(3);
		root.left.left.left=new TreeNode(3);
		root.left.right=new TreeNode(1);
		root.left.right.right=new TreeNode(1);
		System.out.println(maxDis(root));
	}
	public static int maxDis(TreeNode root) {
		Depth(root);
		return root.res;
	}
	public static int Depth(TreeNode root) {
		if(root==null) {
			return 0;
		}
		if(root.left!=null) {
			root.l_depth=Depth(root.left);  // 左子树最大高度
			root.res=Math.max(root.res,root.left.res);  // 更新最大距离
		}
		if(root.right!=null) {
			root.r_depth=Depth(root.right);  // 右子树最大高度
			root.res=Math.max(root.res,root.right.res);  // 更新最大距离
		}
		int sum=root.l_depth+root.r_depth;  // 当路径经过该节点时的距离
		root.res=Math.max(root.res, sum);  // 更新最大距离
		return Math.max(root.l_depth,root.r_depth)+1;  //返回该节点高度
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值