Advertisement
leoanjos

Validate Binary Search Tree

May 23rd, 2022
785
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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 isValidBST(TreeNode *root, int mn = -1, int mx = -1, bool has_mn = false, bool has_mx = false) {
  15.         if (root == nullptr) {
  16.             return true;
  17.         }
  18.        
  19.         int curr = root->val;
  20.         if ((has_mn && curr <= mn) || (has_mx && curr >= mx)) {
  21.             return false;
  22.         }
  23.        
  24.         return isValidBST(root->left, mn, curr, has_mn, true) && isValidBST(root->right, curr, mx, true, has_mx);
  25.     }
  26. };
Advertisement
RAW Paste Data Copied
Advertisement