530. Minimum Absolute Difference in BST*

530. Minimum Absolute Difference in BST*

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

题目描述

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.

C++ 实现 1

对于 BST 来说, 对其进行中序遍历, 得到的序列是有序的. 那么要找最小的 absolute minimum, 那么其实就是找有序序列中, 两个相邻元素的最小 absolute minimum. 因此, 需要用 prev 来记录前一个节点.

/**
 * 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 {
private:
    TreeNode *prev; // 记录中序遍历的前一个节点
    int res = INT32_MAX;
    void inorder(TreeNode *root) {
        if (!root) return;
        inorder(root->left);
        if (prev) res = min(res, root->val - prev->val);
        prev = root;
        inorder(root->right);
    }
public:
    int getMinimumDifference(TreeNode* root) {
        inorder(root);
        return res;
    }
};
发布了327 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Eric_1993/article/details/104504957