530. Minimum Absolute Difference in BST
来源:互联网 发布:狸猫视频剪辑软件下载 编辑:程序博客网 时间:2024/06/16 05:28
题目:
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).思路:
本题思路比较简单,求任意结点间的差值绝对值,可以先利用中序遍历存储结点,因为中序遍历的结点是按升序排列的,所以只要比较相邻点的差值即可
代码:
/** * 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> res; InOrder(root,res); int min =res.back(),diff; for(int i = 1;i<res.size();i++) { diff = res[i] - res[i-1]; min = min < diff?min:diff; } return min; }private: void InOrder(TreeNode* T,vector<int>& res){ if(T != NULL){ //访问左子结点 InOrder(T->left,res); //访问根节点 res.push_back(T->val); //访问右子结点 InOrder(T->right,res); } }};
阅读全文
1 0
- Leetcode-530. Minimum Absolute Difference in BST
- 【Leetcode】530. Minimum Absolute Difference in BST
- Leetcode 530. Minimum Absolute Difference in BST
- 530. Minimum Absolute Difference in BST
- 530. Minimum Absolute Difference in BST
- [leetcode] 530. Minimum Absolute Difference in BST
- 530. Minimum Absolute Difference in BST
- LeetCode-530. Minimum Absolute Difference in BST
- LeetCode 530. Minimum Absolute Difference in BST
- [LeetCode]530. Minimum Absolute Difference in BST
- 530. Minimum Absolute Difference in BST
- LeetCode | 530. Minimum Absolute Difference in BST
- leetcode 530. Minimum Absolute Difference in BST
- [leetcode]-530. Minimum Absolute Difference in BST
- 530. Minimum Absolute Difference in BST
- [LeetCode]530. Minimum Absolute Difference in BST
- 530. Minimum Absolute Difference in BST
- [leetcode]: 530. Minimum Absolute Difference in BST
- const详解
- 以太坊历史
- Mysql数据库操作
- java并发学习----CountDownLatch
- OSI 七层模型详解
- 530. Minimum Absolute Difference in BST
- HDU4764 Stone 巴什博奕|签到
- Mongo聚合
- 树莓派3移植安卓系统指导
- Java队列
- VS2012下如何生成和调用DLL
- HDU 2580 a simple stone game K倍减法博弈游戏
- 最新面试题2017
- MVP框架简介