EasyNo. 0543

Diameter of Binary Tree — LeetCode 543 Python Solution

Topics
Tree, Depth-First Search, Binary Tree
On study lists
NeetCode 150 and Grind 75
Reading time
3 min

The problem

Given the root of a binary tree, return 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.

Example

Input
root = [1,2,3,4,5]
Output
3
Explanation
3 is the length of the path [4,2,1,3] or [5,2,1,3].

Python solution

PythonSolution
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def diameterOfBinaryTree(self, root: TreeNode) -> int:
        def dfs(root):
            if root is None:
                return 0
            nonlocal ans
            left, right = dfs(root.left), dfs(root.right)
            ans = max(ans, left + right)
            return 1 + max(left, right)

        ans = 0
        dfs(root)
        return ans

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 543. Diameter of Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0538Convert BST to Greater TreeMedium
0098Validate Binary Search TreeMedium
0099Recover Binary Search TreeMedium
0100Same TreeEasy
0101Symmetric TreeEasy
0104Maximum Depth of Binary TreeEasy

Frequently asked questions

How hard is LeetCode 543. Diameter of Binary Tree?

LeetCode 543. Diameter of Binary Tree is rated Easy on LeetCode.

What is the time complexity of LeetCode 543. Diameter of Binary Tree?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 543. Diameter of Binary Tree?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 543. Diameter of Binary Tree cover?

LeetCode 543. Diameter of Binary Tree is tagged Tree, Depth-First Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.