Diameter of a Binary Tree

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

Return3, 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.

Source: https://www.geeksforgeeks.org/diameter-of-a-binary-tree/

The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two end nodes.

The diagram below shows two trees each with diameter nine, the leaves that form the ends of a longest path are shaded (note that there is more than one path in each tree of length nine, but no path longer than nine nodes).

Solution & Analysis

The diameter of a tree T is the largest of the following quantities:

* the diameter of T’s left subtree * the diameter of T’s right subtree * the longest path between leaves that goes through the root of T (this can be computed from the heights of the subtrees of T)

LeetCode

Straightforward implementation:

O(n^2) time complexity

Optimized implementation:

The above implementation can be optimized by calculating the height in the same recursion rather than calling a height() separately. Thanks to Amar for suggesting this optimized version. This optimization reduces time complexity to O(n).

O(n) time complexity

Reference

https://www.geeksforgeeks.org/diameter-of-a-binary-tree/

Diameter of a Binary Tree in O(n) [A new method]

Diameter of an N-ary tree

http://www.cs.duke.edu/courses/spring00/cps100/assign/trees/diameter.html

Last updated

Was this helpful?