Logo for ammarahmed.ca
Easy
Dec 24, 2025
#binary-tree
#dfs

543. Diameter of Binary Tree

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. This path may or may not pass through the root.

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

Example 1:

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

Example 2:

1Input: root = [1,2] 2Output: 1
  • The number of nodes in the tree is in the range [1, 104].
    • -100 <= Node.val <= 100

      Constraints:

      Notes

      Intuition

      The diameter passes through some node where the path goes down through its left and right subtrees. At each node, left_height + right_height is a candidate for the diameter. Track the maximum across all nodes.

      Implementation

      Use DFS that returns the height of each subtree while updating a global result. Base case: null node returns 0. For each node, compute left and right heights recursively. Update the global maximum with left + right (the path through this node). Return 1 + max(left, right) as this subtree's height.

      Edge-cases

      In Python, use nonlocal to modify variables from an enclosing scope within a nested function. The diameter could be entirely within one subtree.

      • Time: O(n) — visit each node once
        • Space: O(n) — recursion stack depth in worst case

          Complexity

          Solution

          1from typing import Optional 2from lcutils import TreeNode 3 4# Definition for a binary tree node. 5# class TreeNode: 6# def __init__(self, val=0, left=None, right=None): 7# self.val = val 8# self.left = left 9# self.right = right 10class Solution: 11 def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: 12 res = 0 13 def dfs(root: Optional[TreeNode]) -> int: 14 nonlocal res 15 if not root: 16 return 0 17 left = dfs(root.left) 18 right = dfs(root.right) 19 res = max(res, left + right) 20 return 1 + max(left, right) 21 22 dfs(root) 23 return res 24 25 26 27 28if __name__ == "__main__": 29 # Include one-off tests here or debugging logic that can be run by running this file 30 # e.g. print(solution.two_sum([1, 2, 3, 4], 3)) 31 solution = Solution() 32