Leetcode 530. Minimum Absolute Difference in BST

Posted Deribs4

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

530. Minimum Absolute Difference in BST(LeetCode)

[LeetCode] 530. Minimum Absolute Difference in BST Java

[LeetCode&Python] Problem 530. Minimum Absolute Difference in BST

[leetcode]Binary Search Tree-530. Minimum Absolute Difference in BST

LeetCode 530. Minimum Absolute Difference in BST(在二叉查找树中查找两个节点之差的最小绝对值)

530. Minimum Absolute Difference in BST