题目链接:https://leetcode.cn/problems/minimum-absolute-difference-in-bst/
方法一 迭代
1 方法思想
2 代码实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int getMinimumDifference(TreeNode root) {
if (root == null) return 0;
int result = Integer.MAX_VALUE;
TreeNode last = null;
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
if (last != null){
int diff = root.val - last.val;
result = result > diff ? diff : result;
}
last = root;
root = root.right;
}
return result;
}
}
3 复杂度分析
时间复杂度:
空间复杂度:
4 涉及到知识点
5 总结
方法二 递归
1 方法思想
2 代码实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int result = Integer.MAX_VALUE;
TreeNode pre = null;
public int getMinimumDifference(TreeNode root) {
if (root == null) return 0;
travel(root);
return result;
}
public void travel(TreeNode root){
if (root == null) return;
travel(root.left);
if (pre != null){
int dif = root.val - pre.val;
result = result > dif ? dif : result;
}
pre = root;
travel(root.right);
}
}
3 复杂度分析
时间复杂度:
空间复杂度: