Topic:
Given A binary search tree with non-negative values, find the minimum absolute difference between values of any and both nodes.
Example:
Input: 1 3 / 2output:1explanation:the Minimum Absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
Note:there is at least, nodes and this BST.
test instructions and analysis: given a binary search tree (node is non-negative), it is required to find the minimum value of the absolute difference between any two points. The problem is simple, the direct sequence traversal binary tree, get an ascending list, and then calculate the absolute value of every two number difference, each time and the current minimum is compared, if less than the current minimum value, replace can.
Code:
/** * 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) { //ACT sequence traversal, then compares each adjacent two numbers List<integer > list = new arraylist<> (); Search (list,root); int min = integer.max_value; for (int i=0;i<list.size () -1;i++) { int temp = Math.Abs (List.get (i+1)-list.get (i)); if (temp<min) min = temp; } return min; } private void Search (list<integer> list,treenode node) { if (node!=null) { search (list,node.left); List.add (node.val); Search (list,node.right);}}
[Leetcode] 530. Minimum Absolute difference in BST Java