Leetcode 530 Solution

This article provides solution to leetcode question 530 (minimum-absolute-difference-in-bst)

https://leetcode.com/problems/minimum-absolute-difference-in-bst

Solution

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int getMinimumDifference(TreeNode* root) {
        TreeNode* last = NULL;
        auto p = root;
        stack<TreeNode*> q;
        int min_val = INT_MAX;

        while (p || q.empty() == false)
        {
            while (p)
            {
                q.push(p);
                p = p->left;
            }

            p = q.top();
            q.pop();

            if (last != NULL)
                min_val = min(min_val, (int)abs(last->val - p->val));

            last = p;
            p = p->right;
        }

        return min_val;
    }
};