|
1 | 1 | # The diameter of a tree (sometimes called the width)
|
2 | 2 | # is the number of nodes on the longest path between
|
3 | | -# two end nodes. |
| 3 | +# two end nodes(leftmost leaf node and rightmost leaf node). |
4 | 4 |
|
5 | 5 | # The diameter of a tree T is the largest of the following quantities:
|
6 | | - |
7 | | -# * the diameter of T’s left subtree |
8 | | -# * the diameter of T’s right subtree |
9 | | -# * the longest path between leaves that goes through the |
10 | | -# root of T (this can be computed from the heights of the subtrees of T) |
| 6 | +# the diameter of T’s left subtree |
| 7 | +# the diameter of T’s right subtree |
| 8 | +# the longest path between leaves that goes through the root of T (this can be computed from the heights of the subtrees of T) |
| 9 | + |
| 10 | +# Algorithm: |
| 11 | +# Case 1: if the diameter passes through origin, then diameter is |
| 12 | +# height of left subtree + height of right subtree + 1 (root node) |
| 13 | +# d = lheight + rheight + 1 |
| 14 | + |
| 15 | +# Case 2: if the diameter is not passing through origin |
| 16 | +# Search for diameter in the left subtree and right subtree |
| 17 | +# Pick the larger value of the two subtrees |
| 18 | +# d = max(ldiameter, rdiameter) |
| 19 | + |
| 20 | +# Finally take max of the two values since we do not |
| 21 | +# know if diameter is passing through the root or not |
| 22 | +# d = max(lheight + rheight + 1, max(ldiameter, rdiameter)) |
11 | 23 |
|
12 | 24 | class Node(object):
|
13 | 25 | def __init__(self, data):
|
|
0 commit comments