Skip to content

Commit e4178be

Browse files
authored
Create 783. Minimum Distance Between BST Nodes (#95)
783. Minimum Distance Between BST Nodes
2 parents cde768d + f459466 commit e4178be

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
public: vector<int>store;
14+
15+
void dfs(TreeNode* node){ //dfs traversal
16+
if(node==NULL) return;
17+
store.push_back(node->val);
18+
dfs(node->left); //left call
19+
dfs(node->right); //right call
20+
}
21+
22+
23+
int minDiffInBST(TreeNode* root) {
24+
dfs(root); //function calling
25+
sort(store.begin(),store.end());
26+
int result=INT_MAX;
27+
for(int i=0;i+1<store.size();++i){ //finding two no such that their differnce is minimum
28+
if(store[i+1]-store[i]<result){
29+
result=store[i+1]-store[i];
30+
}
31+
}
32+
return result;;
33+
}
34+
};

0 commit comments

Comments
 (0)