原文链接 783. Minimum Distance Between BST Nodes
Description:
Given a Binary Search Tree (BST) with the root node root
, return the minimum difference between the values of any two different nodes in the tree.
Example :
Input: root = [4,2,6,1,3,null,null]
Output: 1
Explanation:
Note that root is a TreeNode object, not an array.
The given tree [4,2,6,1,3,null,null] is represented by the following diagram:
4
/ \
2 6
/ \
1 3
while the minimum difference in this tree is 1, it occurs between node 1 and node 2, also between node 3 and node 2.
Note:
- The size of the BST will be between 2 and
100
. - The BST is always valid, each node's value is an integer, and each node's value is different.
思路:本题要求返回二叉搜索树两个结点间的最小距离。直接使用中序遍历,将结点依次保存在数组中,再从数组中找两个相邻的元素最小差值。
C++ 代码
/**
* 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 minDiffInBST(TreeNode* root) {
vector<int> vec;
dfs(root,vec);
int res = INT_MAX;
for(int i=1; i<vec.size(); i++){
res = min(res, vec[i]-vec[i-1]);
}
return res;
}
void dfs(TreeNode* root, vector<int> & vec)
{
if(root == nullptr)
return ;
dfs(root->left,vec);
vec.push_back(root->val);
dfs(root->right,vec);
}
};
运行时间:4ms
运行内存:11.8M
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于