congr / world

2 stars 1 forks source link

LeetCode : 530. Minimum Absolute Difference in BST #518

Closed congr closed 5 years ago

congr commented 5 years ago

https://leetcode.com/problems/minimum-absolute-difference-in-bst/

image

congr commented 5 years ago
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int getMinimumDifference(TreeNode root) {
        minDiff = Integer.MAX_VALUE; // !!!
        inorder(root);
        return minDiff;
    }

    int minDiff;
    TreeNode pre;
    void inorder(TreeNode root) {
        if (root == null) return;

        inorder(root.left);

        if (pre != null)
            minDiff = Math.min (minDiff, root.val - pre.val);
        pre = root;

        inorder(root.right);
    }
}
congr commented 5 years ago

440 same

congr commented 5 years ago
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int getMinimumDifference(TreeNode root) {
        minDiff = Integer.MAX_VALUE; // !!!
        inorder(root);
        return minDiff;
    }

    int minDiff;
    TreeNode pre;
    void inorder(TreeNode root) {
        if (root == null) return;

        inorder(root.left);

        if (pre != null)
            minDiff = Math.min (minDiff, root.val - pre.val);
        pre = root;

        inorder(root.right);
    }
}