-
Notifications
You must be signed in to change notification settings - Fork 0
/
minAbsSubtract.py
51 lines (38 loc) · 1.19 KB
/
minAbsSubtract.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
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : minAbsSubtract.py
@Time : 2024/10/15 16:32:16
@Author : Zihao Zheng
@Email : [email protected]
'''
class Solution():
def __init__(self):
self.result = float('inf')
self.pre = None
def minAbsSubtract(self,root):
stack=[]
cur=root #引用一个指针
pre=None
result=float('inf')
while cur or stack:
if cur: #访问到最下面的左子树
stack.append(cur)
cur=cur.left
else:
cur=stack.pop() #弹出一个 指针右移
if pre is not None:
result=min(result,cur.val-pre.val)
pre=cur
cur=cur.right
return
def dfs(self,node):
if node is None:
return
self.dfs(node.left)
if self.pre is not None:
self.result=min(self.result,node.val-self.pre.val)
self.pre=node
self.dfs(node.right)
def minAbsSubtract2(self,root):
return