Skip to content

Commit 382456c

Browse files
author
Amogh Singhal
authored
Update diameterOfTree.py
1 parent 40448d6 commit 382456c

File tree

1 file changed

+18
-6
lines changed

1 file changed

+18
-6
lines changed

diameterOfTree.py

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,25 @@
11
# The diameter of a tree (sometimes called the width)
22
# 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).
44

55
# 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))
1123

1224
class Node(object):
1325
def __init__(self, data):

0 commit comments

Comments
 (0)