From e6698cbac457714427f4a9cba6ea2a3ea9eed94c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=98windscape=E2=80=99?= <2462269317@qq.com> Date: Sat, 25 Jan 2025 11:52:09 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B90530.=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=B7=AE.md=E7=9A=84Java=E7=89=88=E6=9C=AC=20?= =?UTF-8?q?=E8=BF=9B=E8=A1=8C=E4=BA=86=E4=BB=A3=E7=A0=81=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E5=8C=96=E5=B9=B6=E6=B7=BB=E5=8A=A0=E4=BA=86=E7=BB=9F=E4=B8=80?= =?UTF-8?q?=E8=BF=AD=E4=BB=A3=E6=B3=95=E7=9A=84=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0530.二叉搜索树的最小绝对差.md | 46 +++++++++++-------- 1 file changed, 28 insertions(+), 18 deletions(-) diff --git a/problems/0530.二叉搜索树的最小绝对差.md b/problems/0530.二叉搜索树的最小绝对差.md index 2533a618..b6d08dbe 100644 --- a/problems/0530.二叉搜索树的最小绝对差.md +++ b/problems/0530.二叉搜索树的最小绝对差.md @@ -153,23 +153,27 @@ public: 递归 ```java class Solution { - TreeNode pre;// 记录上一个遍历的结点 + TreeNode pre; // 记录上一个遍历的结点 int result = Integer.MAX_VALUE; + public int getMinimumDifference(TreeNode root) { - if(root==null)return 0; - traversal(root); - return result; + if (root == null) + return 0; + traversal(root); + return result; } - public void traversal(TreeNode root){ - if(root==null)return; - //左 + + public void traversal(TreeNode root) { + if (root == null) + return; + // 左 traversal(root.left); - //中 - if(pre!=null){ - result = Math.min(result,root.val-pre.val); + // 中 + if (pre != null) { + result = Math.min(result, root.val - pre.val); } pre = root; - //右 + // 右 traversal(root.right); } } @@ -182,22 +186,27 @@ class Solution { TreeNode pre = null; int result = Integer.MAX_VALUE; - if(root != null) + if (root != null) stack.add(root); - while(!stack.isEmpty()){ + + // 中序遍历(左中右),由于栈先入后出,反序(右中左) + while (!stack.isEmpty()) { TreeNode curr = stack.peek(); - if(curr != null){ + if (curr != null) { stack.pop(); - if(curr.right != null) + // 右 + if (curr.right != null) stack.add(curr.right); + // 中(先用null标记) stack.add(curr); stack.add(null); - if(curr.left != null) + // 左 + if (curr.left != null) stack.add(curr.left); - }else{ + } else { // 中(遇到null再处理) stack.pop(); TreeNode temp = stack.pop(); - if(pre != null) + if (pre != null) result = Math.min(result, temp.val - pre.val); pre = temp; } @@ -674,3 +683,4 @@ public class Solution +