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.

Method1 DFS (n time, 1 space)

  • This question is similiar to https://www.gitbook.com/book/bfmc/algorithm/edit\#/edit/master/big-motherfucking-g/binary-tree-maximum-path-sum.md?\_k=4sxwf7
  • We also maintain a global "diameter" value and do dfs.
  • For each node, add up the value of the diameter of its left and right subtree, compare it with the global diameter value.
  • At the end of the dfs function, return 1+max(left, right) to allow its parent callstack to compute its own diameter value.

  • class Solution(object):
      def diameterOfBinaryTree(self, root):
          self.best = 0
          self.dfs(root)
          return self.best
      def dfs(self, root):
          if not root:
              return 0
          left = self.dfs(root.left)
          right = self.dfs(root.right)
          self.best = max(self.best, left + right)
          return 1 + max(left, right)
    

results matching ""

    No results matching ""