-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0543-diameter-of-binary-tree.py
More file actions
34 lines (27 loc) · 863 Bytes
/
0543-diameter-of-binary-tree.py
File metadata and controls
34 lines (27 loc) · 863 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
32
33
34
# time complexity: O(n)
# space complexity: O(n)
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
result = 0
def dfs(node: Optional[TreeNode]):
nonlocal result
if node is None:
return 0
leftResult = dfs(node.left)
rightResult = dfs(node.right)
result = max(result, leftResult + rightResult)
return max(leftResult, rightResult) + 1
dfs(root)
return result
root = TreeNode(1)
root.left = TreeNode(2)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right = TreeNode(3)
print(Solution().diameterOfBinaryTree(root))