aboutsummaryrefslogtreecommitdiff
path: root/min_abs_diff_bst.cpp
diff options
context:
space:
mode:
authorjack <[email protected]>2024-06-14 13:13:15 -0600
committerjack <[email protected]>2024-06-14 13:13:15 -0600
commitd343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch)
tree96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /min_abs_diff_bst.cpp
downloadleetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz
leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip
initial
Diffstat (limited to 'min_abs_diff_bst.cpp')
-rw-r--r--min_abs_diff_bst.cpp27
1 files changed, 27 insertions, 0 deletions
diff --git a/min_abs_diff_bst.cpp b/min_abs_diff_bst.cpp
new file mode 100644
index 0000000..0c0ef82
--- /dev/null
+++ b/min_abs_diff_bst.cpp
@@ -0,0 +1,27 @@
+// 530. Minimum Absolute Difference in BST
+#include "leetcode.h"
+
+/*
+ * given the 'root' of a binary search tree (bst), return the minimum absolute
+ * difference between the values of any two different nodes in the tree
+ */
+
+class Solution {
+ int diff = INT_MAX;
+ TreeNode *prev = NULL;
+ void dfs(TreeNode *root) {
+ if (root->left)
+ dfs(root->left);
+ if (prev)
+ diff = min(diff, abs(prev->val - root->val));
+ prev = root;
+ if (root->right)
+ dfs(root->right);
+ }
+
+public:
+ int getMinimumDifference(TreeNode *root) {
+ dfs(root);
+ return diff;
+ }
+};