mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-12-18 09:10:16 +00:00
bc8df6de31
* [pre-commit.ci] pre-commit autoupdate updates: - [github.com/astral-sh/ruff-pre-commit: v0.2.2 → v0.3.2](https://github.com/astral-sh/ruff-pre-commit/compare/v0.2.2...v0.3.2) - [github.com/pre-commit/mirrors-mypy: v1.8.0 → v1.9.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.8.0...v1.9.0) * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
74 lines
1.6 KiB
Python
74 lines
1.6 KiB
Python
"""
|
|
The diameter/width of a tree is defined as the number of nodes on the longest path
|
|
between two end nodes.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
|
|
|
|
@dataclass
|
|
class Node:
|
|
data: int
|
|
left: Node | None = None
|
|
right: Node | None = None
|
|
|
|
def depth(self) -> int:
|
|
"""
|
|
>>> root = Node(1)
|
|
>>> root.depth()
|
|
1
|
|
>>> root.left = Node(2)
|
|
>>> root.depth()
|
|
2
|
|
>>> root.left.depth()
|
|
1
|
|
>>> root.right = Node(3)
|
|
>>> root.depth()
|
|
2
|
|
"""
|
|
left_depth = self.left.depth() if self.left else 0
|
|
right_depth = self.right.depth() if self.right else 0
|
|
return max(left_depth, right_depth) + 1
|
|
|
|
def diameter(self) -> int:
|
|
"""
|
|
>>> root = Node(1)
|
|
>>> root.diameter()
|
|
1
|
|
>>> root.left = Node(2)
|
|
>>> root.diameter()
|
|
2
|
|
>>> root.left.diameter()
|
|
1
|
|
>>> root.right = Node(3)
|
|
>>> root.diameter()
|
|
3
|
|
"""
|
|
left_depth = self.left.depth() if self.left else 0
|
|
right_depth = self.right.depth() if self.right else 0
|
|
return left_depth + right_depth + 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
from doctest import testmod
|
|
|
|
testmod()
|
|
root = Node(1)
|
|
root.left = Node(2)
|
|
root.right = Node(3)
|
|
root.left.left = Node(4)
|
|
root.left.right = Node(5)
|
|
r"""
|
|
Constructed binary tree is
|
|
1
|
|
/ \
|
|
2 3
|
|
/ \
|
|
4 5
|
|
"""
|
|
print(f"{root.diameter() = }") # 4
|
|
print(f"{root.left.diameter() = }") # 3
|
|
print(f"{root.right.diameter() = }") # 1
|