其他分享
首页 > 其他分享> > [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:

二叉搜索树的最小绝对差。题目即是题意,找到BST里面任意两点差值的最小值。既然是BST那么还是中序遍历,然后找到中序遍历过程中每两个邻居节点val差值的最小值。我这里提供迭代和递归两种实现。两种实现的复杂度是一样的。

时间O(n)

空间O(n)

Java实现 - 迭代

 1 class Solution {
 2     public int getMinimumDifference(TreeNode root) {
 3         int res = Integer.MAX_VALUE;
 4         int prev = Integer.MAX_VALUE;
 5         Stack<TreeNode> stack = new Stack<>();
 6         TreeNode cur = root;
 7         while (cur != null || !stack.isEmpty()) {
 8             while (cur != null) {
 9                 stack.push(cur);
10                 cur = cur.left;
11             }
12             cur = stack.pop();
13             if (prev != Integer.MAX_VALUE) {
14                 res = Math.min(res, cur.val - prev);
15             }
16             prev = cur.val;
17             cur = cur.right;
18         }
19         return res;
20     }
21 }

 

Java实现 - 递归

 1 class Solution {
 2     int min = Integer.MAX_VALUE;
 3     TreeNode prev;
 4 
 5     public int getMinimumDifference(TreeNode root) {
 6         helper(root);
 7         return min;
 8     }
 9 
10     public void helper(TreeNode root) {
11         if (root == null) {
12             return;
13         }
14         helper(root.left);
15         if (prev != null) {
16             min = Math.min(min, root.val - prev.val);
17         }
18         prev = root;
19         helper(root.right);
20     }
21 }

 

相关题目

94. Binary Tree Inorder Traversal

783. Minimum Distance Between BST Nodes - 与本题一模一样

LeetCode 题目总结

标签:cur,val,min,BST,Minimum,530,prev,root
来源: https://www.cnblogs.com/cnoodle/p/13800662.html