[LeetCode] 530. Minimum Absolute Difference in BST
Given the root
of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.
Example 1:
Input: root = [4,2,6,1,3] Output: 1
Example 2:
Input: root = [1,0,48,null,null,12,49] Output: 1
Constraints:
- The number of nodes in the tree is in the range
[2, 104]
. 0 <= Node.val <= 105
Note: This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/
二叉搜索树的最小绝对差。
给你一个二叉搜索树的根节点 root
,返回 树中任意两不同节点值之间的最小差值 。差值是一个正数,其数值等于两值之差的绝对值。
思路是中序遍历。注意对于一个 BST 而言,他的中序遍历的结果是递增的,所以遍历结果里面两个相邻的 node 的差值很好计算。我这里提供迭代和递归两种实现。两种实现的复杂度是一样的。
时间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 - 与本题一模一样