-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path543.py
52 lines (38 loc) · 1.12 KB
/
543.py
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Name: Diameter of Binary Tree
# Link: https://leetcode.com/problems/diameter-of-binary-tree/
# Method: Solving tidbit
# Time: O(n)
# Space: O(d)
# Difficulty: Easy
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
cmax = 0
def rec_dia(self, node):
if not node:
return 0
depth_l = self.rec_dia(node.left)
depth_r = self.rec_dia(node.right)
dia_at = depth_l + depth_r
print(f"At node {node.val} diameter is {dia_at}")
if dia_at > self.cmax:
self.cmax = dia_at
return 1 + max(depth_l, depth_r)
def diameterOfBinaryTree(self, root: TreeNode) -> int:
self.cmax = 0
self.rec_dia(root)
return self.cmax
if __name__ == "__main__":
root = TreeNode(1)
root.left = TreeNode(2)
root.left.left = TreeNode(3)
root.right = TreeNode(4)
root2 = TreeNode(0)
root2.left = TreeNode(1)
sol = Solution()
# print(sol.diameterOfBinaryTree(root))
print(sol.diameterOfBinaryTree(root2))