[Leetcode] 530. Minimum Absolute difference in BST Java

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.