Leetcode530. Minimum Absolute Difference in BST
来源:互联网 发布:mac dock栏随鼠标跳动 编辑:程序博客网 时间:2024/05/16 06:53
Leetcode530. 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.
题目分析:
首先从题意分析,这是一颗二叉搜索树,当你处于根节点的时候,要和左边最大的比较,和右边最小的比较,同时设一个全局变量min,然后不断左递归和右递归。
代码:
class Solution {private: int min1 = INT_MAX - 1;public: int getMinimumDifference(TreeNode* root) { getMini(root); return min1; } void getMini(TreeNode* root) { if (!root) return; int left, right; if (root->left) { left = max(root->left); if (min1 > abs(root->val - left)) min1 = abs(root->val - left); getMini(root->left); } if (root->right) { right = min(root->right); if (min1 > abs(root->val - right)) min1 = abs(right - root->val); getMini(root->right); } } int min(TreeNode* root) { if (root == NULL) return -1; if (root->left == NULL) return root->val; return min(root->left); } int max(TreeNode* root) { if (root == NULL) return -1; if (root->right == NULL) return root->val; return max(root->right); }};
阅读全文
0 0
- leetcode530. Minimum Absolute Difference in BST
- Leetcode530. Minimum Absolute Difference in BST
- LeetCode530. Minimum Absolute Difference in BST
- LeetCode530. Minimum Absolute Difference in BST中序遍历真神奇
- Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- Leetcode-530. Minimum Absolute Difference in BST
- LeetCode: 503.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
- 网易AI英雄风云榜评选:谁是2017 年AI人物 TOP 10? | 评选
- SpringCloud(第 038 篇)idea环境热部署微服务开发
- android 蓝牙功能
- 使用golang开发selpg命令行程序
- 在杨氏矩阵中找数字,存在返回下标,不存在返回“不存在”,杨氏矩阵:每行每列的数字都是递增排序的
- Leetcode530. Minimum Absolute Difference in BST
- SpringCloud(第 039 篇)链接Mysql数据库,通过JpaRepository编写数据库访问
- 【Windows】重叠I/O之事件对象通知
- Android 自定义View---ToggleButton
- 强军征程
- SpringCloud(第 040 篇)链接Mysql数据库,通过CrudRepository编写数据库访问
- 批量删除或修改
- 啊,业务层是否也需要服务化?
- 码农修炼指南,助你掌控全场