题目描述:
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);
}
}
}