From 4f96f64e3d6f54eac978bdea355c22060f80d1ee Mon Sep 17 00:00:00 2001 From: jojoo15 <75017412+jojoo15@users.noreply.github.com> Date: Tue, 18 May 2021 15:59:48 +0200 Subject: [PATCH] =?UTF-8?q?Update=200530.=E4=BA=8C=E5=8F=89=E6=90=9C?= =?UTF-8?q?=E7=B4=A2=E6=A0=91=E7=9A=84=E6=9C=80=E5=B0=8F=E7=BB=9D=E5=AF=B9?= =?UTF-8?q?=E5=B7=AE.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit added python version of code --- .../0530.二叉搜索树的最小绝对差.md | 27 ++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/problems/0530.二叉搜索树的最小绝对差.md b/problems/0530.二叉搜索树的最小绝对差.md index 903ebf78..347d66d1 100644 --- a/problems/0530.二叉搜索树的最小绝对差.md +++ b/problems/0530.二叉搜索树的最小绝对差.md @@ -177,8 +177,29 @@ class Solution { ``` Python: - - +```python +# Definition for a binary tree node. +# 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: TreeNode) -> int: + res = [] + r = float("inf") + def buildaList(root): //把二叉搜索树转换成有序数组 + if not root: return None + if root.left: buildaList(root.left) //左 + res.append(root.val) //中 + if root.right: buildaList(root.right) //右 + return res + + buildaList(root) + for i in range(len(res)-1): // 统计有序数组的最小差值 + r = min(abs(res[i]-res[i+1]),r) + return r +``` Go: @@ -188,4 +209,4 @@ Go: * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -