File tree Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change
1
+ ## 530 Minimum Absolute Difference in BST
2
+
3
+ #### Description
4
+
5
+ [ link] ( https://leetcode.com/problems/minimum-absolute-difference-in-bst/ )
6
+
7
+ ---
8
+
9
+ #### Solution
10
+
11
+ ** 这里讲一下DFS的时间复杂度判断:如果是最坏情况的话,首先因为初始DFS的循环是O(M + N),每个点的最大遍历长度是O(MN),这就是最坏情况的时间复杂度**
12
+
13
+ ---
14
+
15
+ #### Code
16
+
17
+ > 最坏情况下是O(n^2)
18
+
19
+ Iteration:
20
+
21
+ ``` python
22
+ # Definition for a binary tree node.
23
+ # class TreeNode:
24
+ # def __init__(self, x):
25
+ # self.val = x
26
+ # self.left = None
27
+ # self.right = None
28
+
29
+ class Solution :
30
+ def getMinimumDifference (self , root : TreeNode) -> int :
31
+ stack = []
32
+ n = float (' inf' )
33
+ res = float (' inf' )
34
+
35
+ while root or stack:
36
+ if root:
37
+ stack.append(root)
38
+ root = root.left
39
+ else :
40
+ root = stack.pop()
41
+ m = root.val
42
+ res = min (abs (m- n), res)
43
+ n = m
44
+ root = root.right
45
+
46
+ return res
47
+ ```
48
+
49
+ Recursive:
50
+
51
+ ``` python
52
+ # Definition for a binary tree node.
53
+ # class TreeNode:
54
+ # def __init__(self, x):
55
+ # self.val = x
56
+ # self.left = None
57
+ # self.right = None
58
+
59
+ class Solution :
60
+ def getMinimumDifference (self , root : TreeNode) -> int :
61
+ L = []
62
+ def dfs (node ):
63
+ if node.left: dfs(node.left)
64
+ L.append(node.val)
65
+ if node.right: dfs(node.right)
66
+ dfs(root)
67
+ return min (b - a for a, b in zip (L, L[1 :]))
68
+ ```
You can’t perform that action at this time.
0 commit comments