|
| 1 | +""" |
| 2 | +The diameter/width of a tree is defined as the number of nodes on the longest path |
| 3 | +between two end nodes. |
| 4 | +""" |
| 5 | +from __future__ import annotations |
| 6 | + |
| 7 | +from dataclasses import dataclass |
| 8 | + |
| 9 | + |
| 10 | +@dataclass |
| 11 | +class Node: |
| 12 | + data: int |
| 13 | + left: Node | None = None |
| 14 | + right: Node | None = None |
| 15 | + |
| 16 | + def depth(self) -> int: |
| 17 | + """ |
| 18 | + >>> root = Node(1) |
| 19 | + >>> root.depth() |
| 20 | + 1 |
| 21 | + >>> root.left = Node(2) |
| 22 | + >>> root.depth() |
| 23 | + 2 |
| 24 | + >>> root.left.depth() |
| 25 | + 1 |
| 26 | + >>> root.right = Node(3) |
| 27 | + >>> root.depth() |
| 28 | + 2 |
| 29 | + """ |
| 30 | + left_depth = self.left.depth() if self.left else 0 |
| 31 | + right_depth = self.right.depth() if self.right else 0 |
| 32 | + return max(left_depth, right_depth) + 1 |
| 33 | + |
| 34 | + def diameter(self) -> int: |
| 35 | + """ |
| 36 | + >>> root = Node(1) |
| 37 | + >>> root.diameter() |
| 38 | + 1 |
| 39 | + >>> root.left = Node(2) |
| 40 | + >>> root.diameter() |
| 41 | + 2 |
| 42 | + >>> root.left.diameter() |
| 43 | + 1 |
| 44 | + >>> root.right = Node(3) |
| 45 | + >>> root.diameter() |
| 46 | + 3 |
| 47 | + """ |
| 48 | + left_depth = self.left.depth() if self.left else 0 |
| 49 | + right_depth = self.right.depth() if self.right else 0 |
| 50 | + return left_depth + right_depth + 1 |
| 51 | + |
| 52 | + |
| 53 | +if __name__ == "__main__": |
| 54 | + from doctest import testmod |
| 55 | + |
| 56 | + testmod() |
| 57 | + root = Node(1) |
| 58 | + root.left = Node(2) |
| 59 | + root.right = Node(3) |
| 60 | + root.left.left = Node(4) |
| 61 | + root.left.right = Node(5) |
| 62 | + r""" |
| 63 | + Constructed binary tree is |
| 64 | + 1 |
| 65 | + / \ |
| 66 | + 2 3 |
| 67 | + / \ |
| 68 | + 4 5 |
| 69 | + """ |
| 70 | + print(f"{root.diameter() = }") # 4 |
| 71 | + print(f"{root.left.diameter() = }") # 3 |
| 72 | + print(f"{root.right.diameter() = }") # 1 |
0 commit comments