530.二分探索木の最小絶対差



530 Minimum Absolute Difference Binary Search Tree



Given a binary search tree where all nodes are non-negative, find the minimum value of the absolute value of the difference between any two nodes in the tree. Examples : Input: 1 3 / 2 Output: 1 Explanation: The minimum absolute difference is1,among them 2 with 1 The absolute value of the difference is 1(Or 2 with 3)。 note: At least in the tree2Nodes. Source: LeetCode Link: https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst The copyright belongs to the deduction network. Please contact the official authorization for commercial reprint, and please indicate the source for non-commercial reprint.

ミドルオーダー+前のポイントの値を保存します

/** * Definition for a binary tree node. * public class TreeNode { * int val * TreeNode left * TreeNode right * TreeNode(int x) { val = x } * } */ class Solution { TreeNode pre = null int res = Integer.MAX_VALUE public int getMinimumDifference(TreeNode root) { inOrder(root) return res } public void inOrder(TreeNode root) { if(root == null) { return } inOrder(root.left) if(pre != null) { res = Math.min(res, root.val - pre.val) } pre = root inOrder(root.right) } }