leetcode 530. Minimum Absolute Difference in BST(easy)

来源:互联网 发布:同步备份软件 编辑:程序博客网 时间:2024/06/11 04:37

Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.

Example:

Input:   1    \     3    /   2Output:1Explanation: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.

Subscribe to see which companies asked this question.

题目的含义是要找树中任意两个节点间距离最小的值,那么首先把所有的值取出来排序,这样最小值一定在数组相邻的元素之间的差,此时找到最小值即可。

/** * 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:    void getValue(TreeNode* root,vector<int> &value)    {        if(root != NULL)        {             value.push_back(root->val);            getValue(root->left,value);            getValue(root->right,value);        }            }    int getMinimumDifference(TreeNode* root) {        vector<int> value;        getValue(root,value);        sort(value.begin(),value.end());        int len = value.size();        if(len<=1) return 0;        int min = value[1]-value[0];        for(int i=0;i<value.size();i++)        {            if(i+1<len)            {                if(value[i+1]-value[i]< min)                    min = value[i+1]-value[i];            }                    }        return min;    }};


0 0
原创粉丝点击