Minimum Absolute Difference in BST

来源:互联网 发布:java文件命名 编辑:程序博客网 时间:2024/06/05 04:03


Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.

Example:

Input:   1    \     3    /   2Output:1Explanation: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.


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) {
        int res = INT_MAX, pre = -1;
        stack<TreeNode*> s;
        TreeNode *p = root;
        while (p || !s.empty()) {
            while (p) {
                s.push(p);
                p = p->left;
            }
            p = s.top(); s.pop();
            if (pre != -1) res = min(res, p->val - pre);
            pre = p->val;
            p = p->right;
        }
        return res;
    }
};

原创粉丝点击