欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Leetcode 530. Minimum Absolute Difference in BST

程序员文章站 2022-03-04 19:01:10
...

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Leetcode 530. Minimum Absolute Difference in BST

2. Solution

  • Version 1
/**
 * 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) {
        vector<int> values;
        inOrderTranverse(root, values);
        int min = INT_MAX;
        for(int i = 1; i < values.size(); i++) {
            int diff = values[i] - values[i - 1];
            if(min > diff) {
                min = diff;
            }
        }
        return min;
    }

private:
    void inOrderTranverse(TreeNode* root, vector<int>& values) {
        if(!root) {
            return;
        }
        if(root->left) {
            inOrderTranverse(root->left, values);
        }
        values.push_back(root->val);
        if(root->right) {
            inOrderTranverse(root->right, values);
        }
    }
};
  • Version 2
/**
 * 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 min = INT_MAX;
        int current = -1;
        inOrderTranverse(root, min, current);
        return min;
    }

private:
    void inOrderTranverse(TreeNode* root, int& min, int& current) {
        if(!root) {
            return;
        }
        if(root->left) {
            inOrderTranverse(root->left, min, current);
        }
        if(current != -1) {
            if(min > root->val - current) {
                min = root->val - current;
            }
        }
        current = root->val;
        if(root->right) {
            inOrderTranverse(root->right, min, current);
        }
    }
};

Reference

  1. https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/
相关标签: Leetcode