Minimum Absolute Difference In BST Problem


Description

LeetCode Problem 530.

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:

1
2
Input: root = [4,2,6,1,3]
Output: 1

Example 2:

1
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, 10^4].
  • 0 <= Node.val <= 10^5


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int inorderTraverse(TreeNode* root, int& val, int& min_dif) {
        if (root->left != NULL)
            inorderTraverse(root->left, val, min_dif);
        if (val >= 0) 
            min_dif = min(min_dif, root->val - val);
        val = root->val;
        if (root->right != NULL) 
            inorderTraverse(root->right, val, min_dif);
        return min_dif;
    }
    
    int getMinimumDifference(TreeNode* root) {
        auto min_dif = INT_MAX, val = -1;
        return inorderTraverse(root, val, min_dif);
    }
};




Related Posts

Max Area Of Island Problem

LeetCode 695. You are given an m x n binary...

Employee Importance Problem

LeetCode 690. You have a data structure of employee information,...

Cracking The Safe Problem

LeetCode 753. There is a safe protected by a password....

Couples Holding Hands Problem

LeetCode 765. There are n couples sitting in 2n seats...

Contain Virus Problem

LeetCode 749. A virus is spreading rapidly, and your task...

Construct String From Binary Tree Problem

LeetCode 606. Given the root of a binary tree, construct...