[LeetCode] Minimum Absolute Difference in BST

Minimum Absolute Difference in BST

Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.node

Inorder Traverse

Time Complexity
O(logn)
Space Complexity
O(1)code

思路

Because it is a BST, so the smallest absolute number is near each other by using inorder traverse, keep one global minDiff by traversing the whole tree.get

代碼

private int minDiff = Integer.MAX_VALUE;
private TreeNode pre = null;
public int getMinimumDifference(TreeNode root) {
    inorder(root);
    return minDiff;
}

private void inorder(TreeNode root){
    if(root == null) return;
    inorder(root.left);
    if(pre != null) minDiff = Math.min(Math.abs(root.val - pre.val), minDiff);
    pre = root;
    inorder(root.right);
}
相關文章
相關標籤/搜索