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