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
- leetcode 530. Minimum Absolute Difference in BST(easy)
- Leetcode-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
- LeetCode-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
- leetcode 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
- leetcode-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
- leetcode-530. Minimum Absolute Difference in BST
- 常用命令记录
- 设计模式之享元模式
- 操作系统练习
- php curl采集案例
- JFreeChart-图表绘制
- leetcode 530. Minimum Absolute Difference in BST(easy)
- C++ Primer Chapter 7-3
- 算法时间复杂度的表达-渐进符号与主定理
- Spring AOP和动态代理
- 关于python打包成exe
- php服务安装和配置以及和apache整合
- C++ Primer Chapter 7-4
- android 介绍Retrofit的简单使用
- 洛谷 P2604 [ZJOI2010]网络扩容