543. Diameter of Binary Tree

博客介绍了计算二叉树直径的方法。二叉树直径是树中任意两节点间最长路径的长度,该路径可能不经过根节点。给出了递归计算的方法,包括空节点时返回高度为0,传递左右子孩子,索取下一层左右孩子最高深度,处理返回参数并更新边长,最后返回更高深度加当前层高度。

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

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary 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.
在这里插入图片描述

class Solution {
public:
    int maxdiadepth = 0;
    int dfs(TreeNode* root){
        if(root==NULL)
            return 0;
        int leftdepth=dfs(root->left);
        int rightdepth=dfs(root->right);
        if(leftdepth+rightdepth>maxdiadepth)
            maxdiadepth=leftdepth+rightdepth;
        return max(leftdepth +1, rightdepth + 1);
            
    }
    int diameterOfBinaryTree(TreeNode* root) {
        dfs(root);        
        return maxdiadepth;        
    }
};

Base Case:
当Node为空的时候,返回高度为0

Recursive Rule :
传递: 左右子孩子
向下索取:下一层的左孩子和右孩子的最高深度
处理返回上来的参数:边长无非就是左边和右边传递上来的高度合,将其和全球变量比对并且取大保存
向上返回:选择更高的深度并且加上当前层数的高度 (+1) 。最终返回。

class Solution(object):
    def diameterOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        self.maxdepth=0
        self.dfsHelper(root)
        return self.maxdepth
    def dfsHelper(self,root):
        if not root:
            return 0
        leftdepth=self.dfsHelper(root.left)
        rightdepth=self.dfsHelper(root.right)
        if leftdepth+rightdepth>self.maxdepth:
            self.maxdepth=leftdepth+rightdepth
        return max(leftdepth+1,rightdepth+1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值