From 5769c6c7e3af60c6bd4dcaa6441caa1c709303e7 Mon Sep 17 00:00:00 2001 From: ironartisan <54694467+ironartisan@users.noreply.github.com> Date: Tue, 7 Sep 2021 10:26:57 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00530.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=90=9C=E7=B4=A2=E6=A0=91=E7=9A=84=E6=9C=80=E5=B0=8F=E7=BB=9D?= =?UTF-8?q?=E5=AF=B9=E5=80=BC=E5=B7=AE.md=E8=BF=AD=E4=BB=A3Java=E8=A7=A3?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0530.二叉搜索树的最小绝对差.md | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0530.二叉搜索树的最小绝对差.md b/problems/0530.二叉搜索树的最小绝对差.md index ae6719ec..db2ca2d4 100644 --- a/problems/0530.二叉搜索树的最小绝对差.md +++ b/problems/0530.二叉搜索树的最小绝对差.md @@ -171,7 +171,34 @@ class Solution { } } ``` +迭代法-中序遍历 +```java +class Solution { + TreeNode pre; + Stack stack; + public int getMinimumDifference(TreeNode root) { + if (root == null) return 0; + stack = new Stack<>(); + TreeNode cur = root; + int result = Integer.MAX_VALUE; + while (cur != null || !stack.isEmpty()) { + if (cur != null) { + stack.push(cur); + cur = cur.left; // 左节点入栈 + }else { + cur = stack.pop(); // 右节点入栈 + if (pre != null) { + result = Math.min(result, cur.val - pre.val); + } + pre = cur; + cur = cur.right; + } + } + return result; + } +} +``` ## Python 递归