diff options
author | 3gg <3gg@shellblade.net> | 2025-02-05 18:36:31 -0800 |
---|---|---|
committer | 3gg <3gg@shellblade.net> | 2025-02-05 18:36:31 -0800 |
commit | 4689e4e80b479be25f7557d05818f5caa723aafa (patch) | |
tree | 4df25811fe2a9a15b401375178da6537f4b6063f /top-interview-questions/easy/trees/02_valid_binary_search_tree.cc |
Diffstat (limited to 'top-interview-questions/easy/trees/02_valid_binary_search_tree.cc')
-rw-r--r-- | top-interview-questions/easy/trees/02_valid_binary_search_tree.cc | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/top-interview-questions/easy/trees/02_valid_binary_search_tree.cc b/top-interview-questions/easy/trees/02_valid_binary_search_tree.cc new file mode 100644 index 0000000..a071daf --- /dev/null +++ b/top-interview-questions/easy/trees/02_valid_binary_search_tree.cc | |||
@@ -0,0 +1,54 @@ | |||
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: | ||
14 | bool isValidBSTRec(TreeNode* root, int* min, int* max) { | ||
15 | if (root->left && root->right) { | ||
16 | int leftMin, leftMax, rightMin, rightMax; | ||
17 | if (!isValidBSTRec(root->left, &leftMin, &leftMax) || | ||
18 | !isValidBSTRec(root->right, &rightMin, &rightMax)) { | ||
19 | return false; | ||
20 | } | ||
21 | *min = std::min(std::min(leftMin, rightMin), root->val); | ||
22 | *max = std::max(std::max(leftMax, rightMax), root->val); | ||
23 | return (leftMax < root->val) && (root->val < rightMin); | ||
24 | } | ||
25 | else if (root->left) { | ||
26 | int leftMin, leftMax; | ||
27 | if (!isValidBSTRec(root->left, &leftMin, &leftMax)) { | ||
28 | return false; | ||
29 | } | ||
30 | *min = std::min(leftMin, root->val); | ||
31 | *max = std::max(leftMax, root->val); | ||
32 | return (leftMax < root->val); | ||
33 | } | ||
34 | else if (root->right) { | ||
35 | int rightMin, rightMax; | ||
36 | if (!isValidBSTRec(root->right, &rightMin, &rightMax)) { | ||
37 | return false; | ||
38 | } | ||
39 | *min = std::min(rightMin, root->val); | ||
40 | *max = std::max(rightMax, root->val); | ||
41 | return (root->val < rightMin); | ||
42 | } | ||
43 | else { | ||
44 | *min = *max = root->val; | ||
45 | return true; | ||
46 | } | ||
47 | } | ||
48 | |||
49 | bool isValidBST(TreeNode* root) { | ||
50 | if (!root) return true; | ||
51 | int minVal, maxVal; | ||
52 | return isValidBSTRec(root, &minVal, &maxVal); | ||
53 | } | ||
54 | }; | ||