-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0530-minimum-absolute-difference-in-bst.py
More file actions
38 lines (30 loc) · 949 Bytes
/
0530-minimum-absolute-difference-in-bst.py
File metadata and controls
38 lines (30 loc) · 949 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
35
36
37
38
# time complexity: O(nlogn)
# 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 getMinimumDifference(self, root: Optional[TreeNode]) -> int:
nodeList = []
def traverse(node: Optional[TreeNode]):
nonlocal nodeList
if node is None:
return
nodeList.append(node.val)
traverse(node.left)
traverse(node.right)
traverse(root)
nodeList.sort()
minDif = float("inf")
for i in range(1, len(nodeList)):
minDif = min(minDif, nodeList[i] - nodeList[i-1])
return minDif
root = TreeNode(4)
root.left = TreeNode(2)
root.left.left = TreeNode(1)
root.left.right = TreeNode(3)
root.right = TreeNode(6)
print(Solution().getMinimumDifference(root))