码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 530. Minimum Absolute Difference in BST

时间:2017-03-23 23:28:32      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:abs   new   bin   leetcode   tree node   二叉树   ceil   https   style   

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

标签:abs   new   bin   leetcode   tree node   二叉树   ceil   https   style   

原文地址:http://www.cnblogs.com/Deribs4/p/6607932.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!