530. 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.
Example:
Input: 1 \ 3 / 2 Output: 1 Explanation: The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
Note: There are at least two nodes in this BST.
Approach #1: C++.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int getMinimumDifference(TreeNode* root) { if (root->left != NULL) getMinimumDifference(root->left); if (pre != NULL) { imin = min(imin, root->val - pre->val); } pre = root; if (root->right != NULL) getMinimumDifference(root->right); return imin; } private: int imin = INT_MAX; TreeNode* pre = NULL; };
Appraoch #2: Java.
public class Solution { TreeSet<Integer> set = new TreeSet<>(); int min = Integer.MAX_VALUE; public int getMinimumDifference(TreeNode root) { if (root == null) return min; if (!set.isEmpty()) { if (set.floor(root.val) != null) { min = Math.min(min, root.val - set.floor(root.val)); } if (set.ceiling(root.val) != null) { min = Math.min(min, set.ceiling(root.val) - root.val); } } set.add(root.val); getMinimumDifference(root.left); getMinimumDifference(root.right); return min; } }
At the first time, I want to use c++ to realise above code, I can use set upper_bound to replace set.ceiling but I can't find the suitable method to replace the set.floor.
there are some notes about java syntax:
1. The difference between int and Integer in java.
Approach #3: Python.
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def getMinimumDifference(self, root): """ :type root: TreeNode :rtype: int """ L = [] def dfs(root): if root.left: dfs(root.left) L.append(root.val) if root.right: dfs(root.right) dfs(root) return min(abs(a-b) for a, b in zip(L, L[1:]))
There are some syntax in python:
永远渴望,大智若愚(stay hungry, stay foolish)