首页 > 代码库 > Leetcode 530. Minimum Absolute Difference in BST

Leetcode 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.

标签 Binary Search Tree

类似题目 (E) K-diff Pairs in an Array

 

 

 

思路:迭代后序遍历平衡二叉树,得到左子树的最小绝对值差lmin和左子树最大值maxl,得到右子树的最小绝对值差rmin和右子树最小值minr,然后返回min(lmin,rmin,root.val-maxl,root.val-minr)。

 

代码:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     TreeSet<Integer> ts = new TreeSet();
12     public int getMinimumDifference(TreeNode root) {
13         if (root == null)
14             return Integer.MAX_VALUE;
15         int lmin = getMinimumDifference(root.left);
16         if (ts.floor(root.val) != null) {
17             lmin = Math.min(root.val - ts.floor(root.val), lmin);
18         }
19         int rmin = getMinimumDifference(root.right);
20         if (ts.ceiling(root.val) != null) {
21             rmin = Math.min(ts.ceiling(root.val) - root.val, rmin);
22         }
23         ts.add(root.val);
24         return Math.min(lmin, rmin);
25     }
26 }

 

Leetcode 530. Minimum Absolute Difference in BST