[LeetCode] Minimum Absolute Difference in BST

0

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.

Inorder Traverse

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

思路

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.

代码

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);
}

你可能感兴趣的

载入中...