添加0530.二叉搜索树的最小绝对值差.md迭代Java解法

This commit is contained in:
ironartisan
2021-09-07 10:26:57 +08:00
parent b1f8c998a1
commit 5769c6c7e3

View File

@ -171,7 +171,34 @@ class Solution {
}
}
```
迭代法-中序遍历
```java
class Solution {
TreeNode pre;
Stack<TreeNode> 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
递归