Binary Search Tree-530. Minimum Absolute Difference in BST

Posted 抒抒说

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Binary Search Tree-530. 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.

 

#include <iostream>
#include <vector>
#include <limits.h>
using namespace std;

class Solution {
public:
    int getMinimumDifference(TreeNode* root) {
        if(!root)
            return 0;
        vector<int> InOrderArray;
        getInOrderArray(InOrderArray, root);
        //INT_MAX定义
        //zhidao.baidu.com/question/294243885.html
        int res = INT_MAX;
        for(int i=1; i<InOrderArray.size(); i++){//遍历数组得到相邻两个元素最小的差
            if(InOrderArray[i] - InOrderArray[i-1] < res)
                res = InOrderArray[i] - InOrderArray[i-1];
        }
        return res;
    }
    void getInOrderArray(vector<int> &InOrderArray, TreeNode* root){//通过中序遍历得到一个升序数组
        if(!root)
            return;
        getInOrderArray(InOrderArray, root->left);
        InOrderArray.push_back(root->val);
        getInOrderArray(InOrderArray, root->right);
    }

};
int main()
{
    cout << "Hello world!" << endl;
    return 0;
}

 

以上是关于Binary Search Tree-530. Minimum Absolute Difference in BST的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode in Python] 98 (M) validate binary search tree 验证二叉搜索树

[LeetCode]Unique Binary Search TreesII

99. Recover Binary Search Tree

自平衡二叉(查找树/搜索树/排序树) binary search tree

[Leetcode] Binary search, Divide and conquer--240. Search a 2D Matrix II

python学习:python中的正则表达式函数match和search()的区别