Given a binary tree, determine whether it is a valid binary search tree.
A binary search tree has the following characteristics:
- The left subtree of a node contains only numbers less than the current node.
- The right subtree of a node contains only numbers greater than the current node.
- All left and right subtrees must themselves be binary search trees.
Example 1:
enter: 2 / \ 1 3 output: true
Example 2:
enter: 5 / \ 1 4 / \ 3 6 output: false Explanation: The input is: [5,1,4,null,null,3,6]. The root node has a value of 5, but its right child has a value of 4.
solution:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool isValidBST(TreeNode* root) { 13 return validateRange(root, INT32_MIN, INT32_MAX); 14 } 15 private: 16 bool validateRange(TreeNode* root, int min, int max) 17 { 18 if (root == nullptr) 19 return true; 20 21 if (root->val == INT32_MIN && root->left != nullptr) 22 return false; 23 24 if (root->val == INT32_MAX && root->right != nullptr) 25 return false; 26 27 if (root->val < min || root->val > max) 28 return false; 29 30 bool leftFlag = validateRange(root->left, min, root->val-1); 31 bool rightFlag = validateRange(root->right, root->val+1, max); 32 33 return leftFlag && rightFlag; 34 } 35 };