Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.node
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); }