目录
题目一:二叉搜索树的最小绝对差
题目描述:给你一个二叉搜索树的根节点 root
,返回 树中任意两不同节点值之间的最小差值
思路分析: 二叉搜索树的中序遍历结果可以看做是有序的递增数组
解法一:递归
class Solution {
TreeNode pre; // 记录上一个遍历的结点
int res = Integer.MAX_VALUE; // 结果取最小值,先赋予最大值
public int getMinimumDifference(TreeNode root) {
if (root == null) return 0;
inOrder(root);
return res;
}
public void inOrder(TreeNode root) {
if (root == null) return;
inOrder(root.left);
if (pre != null) { // 防止操作空指针
res = Math.min(res, root.val - pre.val); // 取最小绝对差
}
pre = root; // 更新指针
inOrder(root.right);
}
}
解法二:迭代
class Solution {
TreeNode pre; // 记录上一个遍历的结点
Stack<TreeNode> stack = new Stack<>();
public int getMinimumDifference(TreeNode root) {
if (root == null) return 0;
TreeNode cur = root;
int res = Integer.MAX_VALUE;
while (cur != null || !stack.isEmpty()) {
if (cur != null) {
stack.push(cur); // 将访问节点入栈,入栈顺序4、2、1、3、6
cur = cur.left;
} else {