Advertisement
Guest User

Untitled

a guest
Jan 24th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.12 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.    vector<int> leftNodes;
  11.    vector<int> rightNodes;
  12.    int treeDepth = 0;
  13.  
  14.    bool CheckNode(Node* root) {
  15.        for (int currentNode : leftNodes) {
  16.            if (root->data >= currentNode) {
  17.                return false;
  18.            }
  19.            
  20.        }
  21.        
  22.        for (int currentNode : rightNodes) {
  23.            if (root->data <= currentNode) {
  24.                return false;
  25.            }
  26.        }  
  27.        
  28.        if (root->left != nullptr && root->right != nullptr) {
  29.            if (root->data <= root->left->data || root->data >= root->right->data) {
  30.                return false;
  31.            }
  32.        }
  33.        
  34.        return true;
  35.    }
  36.    
  37.    void RemoveNode(bool _isLeft) {
  38.      if (_isLeft) {
  39.          leftNodes.pop_back();
  40.      }
  41.      else {
  42.          rightNodes.pop_back();
  43.      }
  44.    }
  45.  
  46.    void AddNode(int _value, bool _isLeft) {
  47.      if (_isLeft) {
  48.          leftNodes.push_back(_value);
  49.      }
  50.      else {
  51.          rightNodes.push_back(_value);
  52.      }
  53.    }
  54.    
  55.    bool checkBST(Node* root) {
  56.      treeDepth++;
  57.        
  58.      if (root->left != nullptr && root->right != nullptr) {
  59.          if (!CheckNode(root)) {
  60.              return false;
  61.          }
  62.          
  63.          AddNode(root->data, true);
  64.          
  65.          if (!checkBST(root->left)) {
  66.              return false;
  67.          }
  68.          
  69.          AddNode(root->data, false);
  70.          RemoveNode(true);
  71.          
  72.          if (treeDepth == 1) {
  73.             rightNodes.clear();
  74.             leftNodes.clear();
  75.             AddNode(root->data, false);
  76.          }
  77.          
  78.          if (!checkBST(root->right)) {
  79.              return false;
  80.          }
  81.          RemoveNode(false);
  82.  
  83.      }
  84.      else {
  85.          if (!CheckNode(root)) {
  86.              return false;
  87.          }
  88.      }
  89.          
  90.      treeDepth--;
  91.      return true;
  92.    }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement