Minimum Absolute Difference in BST - Tree - Easy - LeetCode
💻 coding

Minimum Absolute Difference in BST - Tree - Easy - LeetCode

1 min read 157 words
1 min read
ShareWhatsAppPost on X
  • 1The problem involves finding the minimum absolute difference between values of any two nodes in a binary search tree.
  • 2An example demonstrates that the minimum absolute difference is 1, derived from nodes with values 2 and 1 or 2 and 3.
  • 3The solution uses an in-order traversal with a time complexity of O(n) and a space complexity of O(1).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The problem involves finding the minimum absolute difference between values of any two nodes in a binary search tree."

Minimum Absolute Difference in BST - Tree - Easy - LeetCode

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.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * public int val;
 * public TreeNode left;
 * public TreeNode right;
 * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
public class Solution {
 int min = int.MaxValue;
 int? prev = null;
 public int GetMinimumDifference(TreeNode root) {
 InOrder(root);
 return min;
 }
 
 private void InOrder(TreeNode root){
 if(root == null){
 return;
 }
 
 InOrder(root.left);
 if(prev!=null){
 min = Math.Min(Math.Abs(root.val-(int)prev),min);
 }
 prev = root.val;
 InOrder(root.right);
 }
}

Time Complexity: O(n)

Space Complexity: O(1)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 7 October 2020 · 1 min read · 157 words

Part of AskGif Blog · coding

You might also like

Minimum Absolute Difference in BST - Tree - Easy - LeetCode | AskGif Blog