-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC-783.cpp
More file actions
36 lines (32 loc) · 779 Bytes
/
Copy pathLC-783.cpp
File metadata and controls
36 lines (32 loc) · 779 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <climits>
#include <string>
using namespace std;
/**
* 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:
/**
* Concepts: In-order Traversal
*/
int minDiffInBST(TreeNode* root) {
int minDiff = INT_MAX, val = -1;
inorder(root, val, minDiff);
return minDiff;
}
void inorder(TreeNode* node, int& val, int& minDiff) {
if (node->left)
inorder(node->left, val, minDiff);
if (val >= 0)
minDiff = min(minDiff, node->val - val);
val = node->val;
if (node->right)
inorder(node->right, val, minDiff);
}
};