LeetCode 543 diameter-of-binary-tree

LeetCode 543

需要求的是: 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.

那么经过某个点的最长路径可以是,他的左边到自己的最长路径(左高度 -1),加上自己,加上右边到自己的最长路径(右高度-1)。
可以考虑边遍历这个树,边求出左高,右高,和经过自己的最大长度,然后都返回,然后一遍比较一遍保留,到最后的就可以得到结果。

    def diameterOfBinaryTree(self, root: TreeNode) -> int:
        if root == None: return 0
        l, r, d = Solution.traverseTree(root)

        return max(l+r-1, d)

    @staticmethod
    def traverseTree(root: TreeNode): 
        if root == None: return 0, 0, 0
        ll, lr, ld = Solution.traverseTree(root.left)
        rl, rr, rd = Solution.traverseTree(root.right)

        cl = max(ll,lr)
        cr = max(rl,rr)
        cd = max(cl + cr + 1, ld, rd)

        return cl + 1, cr + 1, cd
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值