码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Search Tree-530. Minimum Absolute Difference in BST

时间:2018-01-13 11:22:06      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:str   body   mini   roo   out   中序   enc   std   col   

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

标签:str   body   mini   roo   out   中序   enc   std   col   

原文地址:https://www.cnblogs.com/msymm/p/8278246.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!