leetcode(543):Diameter of Binary Tree

题目要求:
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.
Example:
given a binary tree

          1
         / \
        2   3
       / \     
      4   5  

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

Note: The length of path between two nodes is represented by the number of edges between them.

题目分析:
来求树的直径,也就是求可以不经过根节点的最大的长度。我们之前可以求出树的最大高度,此时来求树的左右深度然后对其进行微小的变形就可以得到经过根的最大的路径长度,然后从经过根节点和不经过根节点的左右子树中的最大路径长度来进行比较。

python代码:

class Solution(object):
    def diameterOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root is None:
            return 0
        return max(self.longest_path(root.left)+self.longest_path(root.right), self.diameterOfBinaryTree(root.left), self.diameterOfBinaryTree(root.right))


    def longest_path(self, root):
        if root:
            if root.left is None and root.right is None:
                return 1
            return 1 + max(self.longest_path(root.left), self.longest_path(root.right))
        return 0

看一下大佬们的做法:大佬们省去了重复的计算,利用了类变量来作为全局变量来使用。

def diameterOfBinaryTree(self, root):
    self.best = 1
    def depth(root):
        if not root: return 0
        ansL = depth(root.left)
        ansR = depth(root.right)
        self.best = max(self.best, ansL + ansR + 1)
        return 1 + max(ansL, ansR)

    depth(root)
    return self.best - 1

我一直觉得上面的那种算法,为什么要设计为减1的形式,可以直接全部减一,都不需要加1的操作,微做改进:

    def diameterOfBinaryTree(self, root):
        self.best = 0
        def depth(root):
            if not root: return 0
            ansL = depth(root.left)
            ansR = depth(root.right)
            self.best = max(self.best, ansL + ansR)
            return 1 + max(ansL, ansR)
        depth(root)
        return self.best

上述算法的关键,也是当前已有的记录最长路径与新的最长路径的最大值,所以,需要一个记录已有的最长路径的全局变量,也就是类变量来记录。

class Solution(object):
    def diameterOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.ans = 0

        def depth(p):
            if not p: return 0
            left, right = depth(p.left), depth(p.right)
            self.ans = max(self.ans, left+right)
            return 1 + max(left, right)

        depth(root)
        return self.ans

好吧,上面的思路与我微调整的思路是一样的,说明大家的看法是一致的。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值