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.

Given a binary tree

         / \
        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.


the pass of two nodes are the sum of maximum heights of left, right subtrees.

Python Solution

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

class Solution:
    def diameterOfBinaryTree(self, root: TreeNode) -> int:
        if root == None:
            return 0
        left_max = self.max_height(root.left)
        right_max = self.max_height(root.right)

        return max(self.diameterOfBinaryTree(root.left), self.diameterOfBinaryTree(root.right), left_max + right_max)
    def max_height(self, root):
        if root == None:
            return 0
        left = self.max_height(root.left)
        right = self.max_height(root.right)
        return max(left, right) + 1
  • Time complexity: O(N).
  • Space complexity: O(N).

One Thought to “LeetCode 543. Diameter of Binary Tree”

Leave a Reply

Your email address will not be published. Required fields are marked *