代码随想录之二叉搜索树的最小绝对值差

本题在力扣530
本题的思想学习于代码随想录

JAVA版本:
思路:本题是二叉排序树,所以我们进行中序遍历就能将二叉树按照递增的顺序来进行排序,然后我们只需要比较两个相邻的结点找到最小值即可。

解法1:
递归:思路与上题验证二叉搜索树有着相同的思想,使用pre结点来保存上一个结点,然后进行节点之间的比较。

class Solution {
    TreeNode pre;//用来记录上一个结点
    int result = Integer.MAX_VALUE; //我们要找到最新的绝对值的差,所以我们设置一个最大值
    public int getMinimumDifference(TreeNode root) {
    if(root==null)return 0;
       traversal(root);
       return result;
    }

    public void traversal(TreeNode root){
        if(root==null)return;
        //中序遍历
        //左
         traversal(root.left);
        //中,中间的就是结果
        //前一个节点不为空就进行比较
        if(pre!=null){
            result = Math.min(result,root.val-pre.val);
        }
        pre = root;
        //右
        traversal(root.right);
    }
}

解法2:
迭代的思想去输出,将中序遍历的迭代法改善一下即可。

class Solution {
    public int getMinimumDifference(TreeNode root) {
        TreeNode pre = null; //声明一个之前的结点
        Stack<TreeNode> 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;
    }
}

解法3: 将该二叉树使用中序遍历得到一个新的数组,再在数据中找到两个两个之间的最小绝对值的差。(该方法不再写出)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值