24.二叉搜索树的最小绝对差

发布时间 2023-09-07 20:34:14作者: autumnmoonming

530.二叉搜索树的最小绝对差

1、概要

给你一棵所有节点为非负值的二叉搜索树,请你计算树中任意两节点的差的绝对值的最小值。

注意是二叉搜索树,二叉搜索树可是有序的。想成在一个有序数组上求最值,求差值

要学会在递归遍历的过程中如何记录前后两个指针,这也是一个小技巧

2、思路

递归

在二叉搜素树中序遍历的过程中,我们就可以直接计算了。需要用一个pre节点记录一下cur节点的前一个节点。

		if(pre!=null){
            result = Math.min(result,root.val-pre.val);
        }
        pre = root;

迭代

		TreeNode pre = null;
        int result = Integer.MAX_VALUE;
		````
        if(pre != null)
                    result = Math.min(result, temp.val - pre.val);
        pre = temp;
		

3、代码

class Solution {
    TreeNode pre = null;⭐⭐⭐
    int result = Integer.MAX_VALUE;⭐⭐⭐
    public int getMinimumDifference(TreeNode root) {
        //reCurSion(root);
        iteRaTion(root);
        return result;
    }

    public void iteRaTion(TreeNode node){
        if(node == null){return;}
        Stack<TreeNode> stack = new Stack<>();
        stack.push(node);
        while(!stack.isEmpty()){
            TreeNode cur = stack.pop();
            if(cur!=null){
                if(cur.right!=null){
                    stack.push(cur.right);
                }
                stack.push(cur);
                stack.push(null);
                if(cur.left!=null){
                    stack.push(cur.left);
                }
            }else{
                cur = stack.pop();
                if(pre !=null){
                    result = Math.min(result,cur.val-pre.val);⭐⭐⭐
                }
                pre = cur;⭐⭐⭐
            }

        }
    }

    public void reCurSion(TreeNode node){
        if(node == null){
            return ;
        }
        reCurSion(node.left);
        if(pre != null){
            result = Math.min(result,node.val-pre.val);⭐⭐⭐
        }
        pre = node;
        reCurSion(node.right);
    }
}