leetcode(543). Diameter of Binary Tree

problem

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.

分析

这个问题就是找到一棵二叉树中两个节点之间最远的距离,其实也就是对任意的节点左右两棵子树深度的和的最大值,因此这里只要对求树的深度的代码做一点修改即可。

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    #self要定义在有self的地方
    def diameterOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.best = 0
        def depth(r):
            if r == None:
                return 0
            else:
                l = depth(r.left)
                r = depth(r.right)
                self.best = max(self.best, l+r)
                return 1 + max(l, r)

        depth(root)
        return self.best

总结

这个问题让我学会更加灵活的运用了递归算法,也就是利用递归算法的中间值l = depth(r.left),r = depth(r.right), self.best = max(self.best, l+r) ,使用中间值修改全局变量进行记录,这样时间复杂度不变却增加了一个遍历的功能,获得每个节点的左右子树深度。

note:
这样的应用通常都是原问题与递归问题有一定联系,例如这里原问题是所有节点的左右子树深度和的最大值,递归问题是求树的深度,所以在递归中就会求到所有节点为根的树的深度,这样就将两个问题联系了起来。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值