mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Update 0530.二叉搜索树的最小绝对差.md - 增加了python3版本的迭代解法
This commit is contained in:
@ -222,6 +222,26 @@ class Solution:
|
|||||||
for i in range(len(res)-1): // 统计有序数组的最小差值
|
for i in range(len(res)-1): // 统计有序数组的最小差值
|
||||||
r = min(abs(res[i]-res[i+1]),r)
|
r = min(abs(res[i]-res[i+1]),r)
|
||||||
return r
|
return r
|
||||||
|
|
||||||
|
# 迭代法-中序遍历
|
||||||
|
class Solution:
|
||||||
|
def getMinimumDifference(self, root: TreeNode) -> int:
|
||||||
|
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: # 当前节点和前节点的值的差值
|
||||||
|
result = min(result, cur.val - pre.val)
|
||||||
|
pre = cur
|
||||||
|
cur = cur.right
|
||||||
|
return result
|
||||||
|
|
||||||
```
|
```
|
||||||
Go:
|
Go:
|
||||||
> 中序遍历,然后计算最小差值
|
> 中序遍历,然后计算最小差值
|
||||||
|
Reference in New Issue
Block a user