mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 07:06:42 +08:00
修改0530.二叉搜索树的最小绝对差.md的Java版本 进行了代码格式化并添加了统一迭代法的注释
This commit is contained in:
@ -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
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
</a>
|
||||
|
||||
|
Reference in New Issue
Block a user