• Sign Up
• Login
• API
• FAQ
• Tools
• Archive
SHARE
TWEET

# Minimum Distance Between BST Nodes

a guest Apr 8th, 2020 109 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. /**
2.  * Definition for a binary tree node.
3.  * struct TreeNode {
4.  *     int val;
5.  *     struct TreeNode *left;
6.  *     struct TreeNode *right;
7.  * };
8.  */
9.
10. long max(long a, long b){
11.     return (a > b)? a: b;
12. }
13.
14. long min(long a, long b){
15.     return (a < b)? a: b;
16. }
17.
18. long Abs(long a, long b){
19.     return (a > b)? a - b: b - a;
20. }
21.
22. typedef struct Node{
23.     long mx;
24.     long mn;
25. }Node;
26.
27. long mn;
28.
29. Node findMinDiff(struct TreeNode* root){
30.     Node node = {INT_MIN, INT_MAX};
31.     if(!root)
32.         return node;
33.     Node left = findMinDiff(root->left);
34.     Node right = findMinDiff(root->right);
35.
36.     mn = min(mn, Abs(root->val, left.mx));
37.     mn = min(mn, Abs(root->val, right.mn));
38.
39.     node.mn = min(root->val, left.mn);
40.     node.mx = max(root->val, right.mx);
41.
42.     return node;
43. }
44.
45. int minDiffInBST(struct TreeNode* root){
46.     mn = INT_MAX;
47.     Node node = findMinDiff(root);
48.
49.     return mn;
50. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.
Top