543. 二叉树的直径

3 篇文章 0 订阅
1 篇文章 0 订阅

在这里插入图片描述

思路

其实就是求每个节点左右子树高度和的最大值
可以结合树的深度的递归求法,在递归的同时记录每个节点高度和的最大值

class Solution(object):
    def __init__(self):
         self.depth_max = 0
    def diameterOfBinaryTree(self, root):
        if not root:
            return 0
        def depth(root):
            if not root:
                return 0
            # if not root.left or not root.right:
            #     return 1
            lmax = depth(root.left)
            rmax = depth(root.right)
            self.depth_max = max(self.depth_max, lmax + rmax)
            return max(lmax, rmax) + 1
        depth(root)
        return self.depth_max

思路二

三种可能

  • 不包含节点x,则结果为左子树最大直径
  • 不包含节点x,则结果为右子树最大直径
  • 包含节点x,则结果为左子树深度+右子树深度+1

返回三种情况中的最大值

class Solution(object):
    def diameterOfBinaryTree(self, root):
        if not root:
            return 0
        l = self.diameterOfBinaryTree(root.left)  #左子树最大直径
        r = self.diameterOfBinaryTree(root.right)  #右子树最大直径
        lh = self.height(root.left)    #左子树深度
        rh = self.height(root.right)   #右子树深度
        return max(l,r,lh+rh)
        
     
   #计算树的深度   
    def height(self,root):
        if not root:
            return 0
        if not root.left and not root.right:
            return 1
        return max(self.height(root.left), self.height(root.right)) + 1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值