LeetCode OJ 543 Diameter of Binary Tree [Easy]

本文介绍了一种计算二叉树最长路径长度的方法。通过递归地寻找每个节点的最大深度,并利用这些深度来确定通过该节点的最长路径。最终找出整棵树的最长路径。

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

题目描述:

Given a binary tree,you need to compute the length of the diameter of the tree. The diameter of abinary tree is the length of the longest path between any two nodes in a tree.This path may or may not pass through the root.

Example:
Given a binary tree

          1

         / \

        2  3

       / \    

      4  5   

Return 3, which isthe length of the path [4,2,1,3] or [5,2,1,3].

题目理解:

给一个二叉树,计算二叉树的最长的路径

题目分析:

1.  对于每一个节点,通过该节点的最长路径 = 该节点左子数最大深度 + 该节点右子数最大深度;

2.  计算通过每一节点的最长路径,取最大值;

3.  使用递归,极限情况是子树为null,此时返回0,即子树的深度为0

4.  使用递归,非极限情况,返回的是左/右子树的深度,左/右子树的深度  = max(子树的左子树深度left,子树的右子树深度right)+1, 这里的1表示加上该子树的根节点。

5.  对下图的递归的解释:

             1

            / \

          2   3

         / \    

       4   5

              \

               6

       4/6/3的左右子树深度为0;

       5的左子树深度为0,右子树(6)深度为0+1=1;

       2的左子树(4)深度为0+1=1,右子树(5)深度为 = max((5)的左子树深度0,(5)的右子树深度1)+1=2;

       1右子树(3)的深度为0+1=1,的左子树(2)深度为 = max((2)的左子树深度1,(2)的右子树深度2)+1=3;

题目解答:

public class Solution {
    int max = 0;
    public int diameterOfBinaryTree(TreeNoderoot) {
        maxDepth(root);
        return max;
    }
    private int maxDepth(TreeNoderoot) {
        if (root== null) return 0;

        intleft = maxDepth(root.left);
        int right= maxDepth(root.right);

        max =Math.max(max, left + right);

        return Math.max(left,right) + 1;
    }
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值