[每日LeetCode] 530. Minimum Absolute Difference in BST

  |   0 评论   |   590 浏览

原文链接 [每日LeetCode] 530. Minimum Absolute Difference in BST

Description:

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).

思路:本题要求二叉搜索树中两个结点绝对值的最小值。这里记住一点,二叉搜索树中序遍历可得排好序的结点,利用这个性质,在中序遍历时更新当前结点和上一个结点的差,注意处理第一个节点没有上一个结点的情况。


C++代码

/**
 * 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;
        inorder(root, pre, res);
        return res;
    }
    void inorder(TreeNode* root, int& pre, int& res){
        if (!root)
            return;
        inorder(root->left, pre, res);
        if (pre != -1)
            res = min(res, root->val - pre);
        pre = root->val;
        inorder(root->right, pre, res);
    }
};

运行时间:8ms

运行内存:21.9M

评论

发表评论