forked from prabhupant/python-ds
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiameter.py
More file actions
31 lines (20 loc) · 694 Bytes
/
diameter.py
File metadata and controls
31 lines (20 loc) · 694 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# Diameter of a binary tree is the longest path between two leaf nodes of a binary tree
# Diameter of a binary tree is maximum value of (left_height + right_height + 1) for each node
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def height(root, ans):
if not root:
return 0
lheight = height(root.left, ans)
rheight = height(root.right, ans)
ans[0] = max(ans[0], 1 + lheight + rheight) # This is for diameter
return 1 + max(lheight, rheight) # This is for height
def diameter(root):
if not root:
return 0
ans = [-9999999999]
h = height(root, ans)
return ans[0]