From 75c7f940d112893dd6a1f89f844b710a87b202e1 Mon Sep 17 00:00:00 2001 From: Lozakaka <102352821+Lozakaka@users.noreply.github.com> Date: Tue, 25 Apr 2023 04:03:17 -0400 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9Ejava=20=E7=B5=B1=E4=B8=80?= =?UTF-8?q?=E8=BF=AD=E4=BB=A3=E6=B3=95-=E4=B8=AD=E5=BA=8F=E9=81=8D?= =?UTF-8?q?=E5=8E=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增java 統一迭代法-中序遍历 --- .../0530.二叉搜索树的最小绝对差.md | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/problems/0530.二叉搜索树的最小绝对差.md b/problems/0530.二叉搜索树的最小绝对差.md index fa1430de..cd24c6fa 100644 --- a/problems/0530.二叉搜索树的最小绝对差.md +++ b/problems/0530.二叉搜索树的最小绝对差.md @@ -174,6 +174,39 @@ class Solution { } } ``` +統一迭代法-中序遍历 +```Java +class Solution { + public int getMinimumDifference(TreeNode root) { + Stack stack = new Stack<>(); + TreeNode pre = null; + int result = Integer.MAX_VALUE; + + if(root != null) + stack.add(root); + while(!stack.isEmpty()){ + TreeNode curr = stack.peek(); + if(curr != null){ + stack.pop(); + if(curr.right != null) + stack.add(curr.right); + stack.add(curr); + stack.add(null); + if(curr.left != null) + stack.add(curr.left); + }else{ + stack.pop(); + TreeNode temp = stack.pop(); + if(pre != null) + result = Math.min(result, temp.val - pre.val); + pre = temp; + } + } + return result; + } +} +``` + 迭代法-中序遍历 ```java