Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Hidden stub code will pass a root argument to the function below. Complete the function to solve the challenge. Hint: you may want to write one or more helper functions.
- The Node struct is defined as follows:
- struct Node {
- int data;
- Node* left;
- Node* right;
- }
- */
- #include <limits.h>
- void find_max(Node* root, int &res){
- // Base Case
- if (!root) return;
- // Change result
- res = max(res, root->data);
- // Iterate over all nodes
- find_max(root->right, res);
- find_max(root->left, res);
- }
- void find_min(Node* root, int &res){
- // Base Case
- if (!root) return;
- // Change result
- res = min(res, root->data);
- // Iterate over all nodes
- find_min(root->right, res);
- find_min(root->left, res);
- }
- bool checkBST(Node* root) {
- // Base Case
- if (!root) return true;
- // Find minimum value in tree
- int res_max = INT_MIN;
- find_max(root->left, res_max);
- // Find maximum value in tree
- int res_min = INT_MAX;
- find_min(root->right, res_min);
- // Check if satisfies BST properties
- if(root->left && res_max >= root->data) return false;
- if(root->right && res_min <= root->data) return false;
- // Check if both left and right subtrees are BSTs
- return checkBST(root->right) && checkBST(root->left);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement