LeetCode 530 Minimum Absolute Difference in BST

来源:互联网 发布:网络摄像机ip搜索软件 编辑:程序博客网 时间:2024/05/17 13:09

题目:

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.

题目链接


题意:

给了一棵二叉搜索树,让你找树上任意两个节点的最小绝对值。

想了半天二叉搜索树的性质,也没用上,无奈写出了二叉树通用解法,,居然没有TLE,,,果然是easy难度的题目啊。。。

普通二叉树的写法是把所有数提取出来排序,之后在找相邻的两个数中的最小差值。

代码如下:

class Solution {public:    vector<int> dic;    void dfs(TreeNode* node) {        dic.push_back(node->val);        if (node->left != NULL) {            dfs(node->left);        }        if (node->right != NULL) {            dfs(node->right);        }    }    int getMinimumDifference(TreeNode* root) {        dfs(root);        sort(dic.begin(), dic.end());        int Min = 0x3f3f3f3f;        for (int i = 1; i < dic.size(); i ++) {            Min = min(Min, dic[i] - dic[i-1]);        }        return Min;    }};


原创粉丝点击