Diameter of Binary Tree
Diameter of Binary Tree is a Easy Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Tree Traversal Patterns (DFS & BFS) pattern, in the Recursive Postorder Traversal subpattern.
Problem statement
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:
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].
Example 2:
Input: root = [1,2] Output: 1
Constraints:
- The number of nodes in the tree is in the range [1, 104].
- -100 <= Node.val <= 100
Topics and companies
Topics: Tree, Depth-First Search, Binary Tree.
Reported in interviews at Facebook, Microsoft, Bloomberg, Amazon, Google, ByteDance, Oracle.
How to practise Diameter of Binary Tree on Thita.ai
Starter code is provided in C, C#, C++, Go, Java, JavaScript and Python. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(n) time and O(h) space.
Open Diameter of Binary Tree in the code editor, or read the Diameter of Binary Tree editorial for a worked solution with its approach and complexity analysis.
Where Diameter of Binary Tree sits in the DSA pattern sheet
- Tree Traversal Patterns (DFS & BFS) pattern guide
- Recursive Postorder Traversal subpattern
- The full DSA patterns sheet
- All coding practice problems
Problems related to Diameter of Binary Tree
Other problems that use the same Recursive Postorder Traversal and Tree Traversal Patterns (DFS & BFS) techniques:
- All Nodes Distance K in Binary Tree — Medium, same subpattern
- Balanced Binary Tree — Easy, same subpattern
- Binary Tree Maximum Path Sum — Hard, same subpattern
- Binary Tree Postorder Traversal — Easy, same subpattern
- Delete Nodes And Return Forest — Medium, same subpattern
- Find Leaves of Binary Tree — Medium, same subpattern
Opening the problem
Progress is saved as you study.