Skip to content

Latest commit

 

History

History
84 lines (61 loc) · 2.17 KB

0543._Diameter_of_Binary_Tree.md

File metadata and controls

84 lines (61 loc) · 2.17 KB

543. Diameter of Binary Tree

难度: Easy

刷题内容

原题连接

内容描述

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.

解题方案

思路 1 - 时间复杂度: O(N^2)- 空间复杂度: O(1)******

对每一个点都求它自身的Diameter,最后取最大值

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

思路 2 - 时间复杂度: O(N)- 空间复杂度: O(N)******

the size of our implicit call stack during our depth-first search is O(N).

刚才中间那些计算maxDepth的状态我们都可以时刻记录下来,即时刻更新res,这样时间可以下降到O(N)

即我们可以在算maxDepth的时候不是像思路一一样每次都重新算,而是把他们都用L和R存起来

beats 100%

class Solution(object):
    def diameterOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.res = 0
        
        def maxDepth(node):
            if not node:
                return 0
            L = maxDepth(node.left)
            R = maxDepth(node.right)
            self.res = max(self.res, L + R)
            return max(L, R) + 1
        
        maxDepth(root)
        return self.res