530. Minimum Absolute Difference in BST
来源:互联网 发布:java商品库存管理代码 编辑:程序博客网 时间:2024/06/06 05:17
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 / 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.
代码:
struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public: void inorderTraverse(TreeNode* root, int& val, int& min_dif) { if (root->left != NULL) inorderTraverse(root->left, val, min_dif); if (val >= 0) min_dif = min(min_dif, root->val - val); val = root->val; if (root->right != NULL) inorderTraverse(root->right, val, min_dif); } int getMinimumDifference(TreeNode* root) { auto min_dif = INT_MAX, val = -1; inorderTraverse(root, val, min_dif); return min_dif; }};
解题思路:
- 采用递归中序遍历的思路,由于是个二叉搜索树,任意两点间差值的最小值肯定是从相邻结点间的差值中选一个;
- 令val = -1 并且设置判别条件 val >= 0 避免了叶子结点与不存在的下一层结点做差,即val - (-1),此处的-1为val的初始值;
- 每次比较min的值与当前两个结点的差值大小,选择较小的哪一个值,赋给min;
- 返回min。
阅读全文
0 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
- leetcode 6. ZigZag Conversion golang实现
- 动态的文件版本的通讯录
- DHTML动态样式的作用
- 达芬奇不相信眼泪!
- Junit和Spring、SpringBoot测试
- 530. Minimum Absolute Difference in BST
- 微信小程序侧边栏+语音记账本(主页面)
- 外观模式
- 解决MySQL命令行工具闪退问题
- java读取xml
- JavaWeb 10 Filter
- jooq入门
- ThinkPHP5请求参数为数组时报错:variable type error:array
- Android Volley框架定制JsonRequest添加Cookie