LeetCode 530. Minimum Absolute Difference in BST

530. Minimum Absolute Difference in BST

Description Submission Solutions

  • Total Accepted: 2742
  • Total Submissions: 5575
  • Difficulty: Easy
  • Contributors: nagasupreeth

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.

Subscribe to see which companies asked this question.


【题目分析】

给定一个二叉搜索树,返回这棵树中任意两个节点差值绝对值最小的那个。


【思路】

对于一颗二叉搜索树,与根节点最接近的节点是它左节点最右边的子节点和右节点最左边的子节点。

1. 以先序的方式遍历二叉搜索树中的每一个节点。

2. 对于当前节点,返回与此节点差值绝对值最小的值。


【java代码】

 1 public class Solution {
 2     public int getMinimumDifference(TreeNode root) {
 3         int minDiff = Integer.MAX_VALUE;
 4         if(root.left != null || root.right != null) {
 5             minDiff = Math.min(minDiff, helper(root));
 6             if(root.left != null)
 7                 minDiff = Math.min(minDiff, getMinimumDifference(root.left));
 8             if(root.right != null)
 9                 minDiff = Math.min(minDiff, getMinimumDifference(root.right));
10         }
11         
12         return minDiff;
13     }
14     
15     public int helper(TreeNode root) {
16         int left = Integer.MAX_VALUE;
17         int right = Integer.MAX_VALUE;
18         if(root.left != null) {
19             TreeNode temp = root.left;
20             while(temp.right != null) temp = temp.right;
21             left = Math.min(left, Math.abs(root.val - temp.val));
22         }
23         
24         if(root.right != null) {
25             TreeNode temp = root.right;
26             while(temp.left != null) temp = temp.left;
27             right = Math.min(right, Math.abs(root.val - temp.val));
28         }
29         return Math.min(left, right);
30     }
31 }

 

转载于:https://www.cnblogs.com/liujinhong/p/6482727.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值