Diameter of Binary Tree
Try to solve the Diameter of Binary Tree problem.
Statement
Given a binary tree, you need to compute the length of the tree’s diameter. 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.
Note: The length of the path between two nodes is represented by the number of edges between them.
Constraints:
- The number of nodes in the tree is in the range .
-
Node.value
Examples
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Diameter of Binary Tree
What is the diameter of the following binary tree?
5
/ \
6 7
/ \
8 9
2
3
4
5
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Try it yourself
Implement your solution in main.py
in the following coding playground.
from ds_v1.BinaryTree.BinaryTree import TreeNode# Definition for a binary tree node# class TreeNode:# def __init__(self, data):# self.data = data# self.left = None# self.right = Nonedef diameter_of_binaryTree(root):# Replace this placeholder return statement with your codereturn -1