Advertisement
CSenshi

isBST? V3

Jun 21st, 2019
374
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.36 KB | None | 0 0
  1. /* 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.  
  2.  
  3. The Node struct is defined as follows:
  4.     struct Node {
  5.         int data;
  6.         Node* left;
  7.         Node* right;
  8.     }
  9. */
  10.  
  11. #include <limits.h>
  12.  
  13. void find_max(Node* root, int &res){
  14.     // Base Case
  15.     if (!root)  return;
  16.    
  17.     // Change result
  18.     res = max(res, root->data);
  19.    
  20.     // Iterate over all nodes
  21.     find_max(root->right, res);
  22.     find_max(root->left, res);
  23. }
  24.  
  25. void find_min(Node* root, int &res){
  26.     // Base Case
  27.     if (!root)  return;
  28.    
  29.     // Change result
  30.     res = min(res, root->data);
  31.    
  32.     // Iterate over all nodes
  33.     find_min(root->right, res);
  34.     find_min(root->left, res);
  35. }
  36.  
  37. bool checkBST(Node* root) {
  38.     // Base Case
  39.     if (!root) return true;
  40.    
  41.     // Find minimum value in tree
  42.     int res_max = INT_MIN;
  43.     find_max(root->left, res_max);
  44.    
  45.     // Find maximum value in tree
  46.     int res_min = INT_MAX;
  47.     find_min(root->right, res_min);
  48.    
  49.     // Check if satisfies BST properties
  50.     if(root->left  && res_max >= root->data)    return false;
  51.     if(root->right && res_min <= root->data)    return false;
  52.    
  53.     // Check if both left and right subtrees are BSTs
  54.     return checkBST(root->right) && checkBST(root->left);    
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement