算法题——Minimum Absolute Difference in BST(JAVA)二叉搜索树

题目描述:
Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.

读题:
对于一颗二叉搜索树,求父节点和子节点绝对值之差的最小值

知识储备:
二叉搜索树
二叉搜索树的特点,小的值在左边,大的值在右边。
遍历:
对于一个已知的二叉查找树,从小到大输出其节点的值;
只需对其进行二叉树的中序遍历即可;
即递归地先输出其左子树,再输出其本身,然后输出其右子树;
遍历的时间复杂度为O(n);

查找:
对于一个已知的二叉查找树x;
在其中查找特定的值k,函数Search返回指向值为k的节点指针;
若找不到则返回0,算法时间复杂度为O(h),h为树的高度;
理想情况下时间复杂度为lgn;

插入:
从根节点开始插入;
如果要插入的值小于等于当前节点的值,在当前节点的左子树中插入;
如果要插入的值大于当前节点的值,在当前节点的右子树中插入;
如果当前节点为空节点,在此建立新的节点,该节点的值为要插入的值,左右子树为空,插入成功;

删除:
如果该没有子女,直接删除;
如果该结点只有一个子女,则删除它,将其子女的父亲改为它的父亲;
如果该结点有两个子女,先用其后继替换该节点,其后继的数据一并加在其后;

解题思路:
中序(左中右)遍历二叉搜索树

提交代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    int res = -1;
    TreeNode parent = null;
    public int getMinimumDifference(TreeNode root) {
        routine(root);
        return res;
    }
    private void routine(TreeNode root) {
        if (root == null) {
            return;
        }
        if (root.left != null) {
            routine(root.left);
        }
        if (parent != null) {
            if (res == -1) {
                res = Math.abs(root.val - parent.val);
            }
            res = Math.min(res, Math.abs(root.val - parent.val));
        }
        parent = root;
        if (root.right != null) {
            routine(root.right);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值