package
0.0.0-20241221191246-b80a13d7bbe0
Repository: https://github.com/yvv4git/go-algorithms.git
Documentation: pkg.go.dev

# README

543. Diameter of Binary Tree

Level - easy

Task

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:

img.png

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, 10^4]. -100 <= Node.val <= 100