java traverse BST once, just record the previous node


  • 0
    L

    public class Solution {

    private TreeNode preNode;
    private int diff;
    
    private void inOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        inOrder(root.left);
        if(preNode != null) {
            int absVal = Math.abs(root.val - preNode.val);
            if(absVal < diff) {
                diff = absVal;
            }
        }
        preNode = root;
        inOrder(root.right);
    }
    
    public int getMinimumDifference(TreeNode root) {
        diff = Integer.MAX_VALUE;
        inOrder(root);
        
        return diff;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.