【32】98. Validate Binary Search Tree
98. Validate Binary Search Tree
- Total Accepted: 139628
- Total Submissions: 620671
- Difficulty: Medium
- Contributors: Admin
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
Example 1:
2 / \ 1 3Binary tree
[2,1,3]
, return true.
Example 2:
1 / \ 2 3Binary tree
[1,2,3]
, return false.Solution 1: Recursion without inorder
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 //Recursion without inorder 13 bool isValidBST(TreeNode* root) { 14 return helper(root, LONG_MAX, LONG_MIN); 15 } 16 17 bool helper(TreeNode* root, long left, long right){ 18 if(!root) return true; 19 if(root -> val >= left || root -> val <= right) return false;//base case 20 return helper(root -> right, left, root -> val) && helper(root -> left, root -> val, right); 21 } 22 };
Solution 2: Inorder
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 //Recursion with inorder 13 bool isValidBST(TreeNode* root) { 14 if(!root) return true; 15 vector<int> in; 16 inorder(root, in); 17 for(int i = 1; i < in.size(); i++){ 18 if(in[i] <= in[i - 1]) return false; 19 } 20 return true; 21 } 22 23 void inorder(TreeNode* root, vector<int> & in){ 24 if(root -> left) inorder(root -> left, in); 25 in.push_back(root -> val); 26 if(root -> right) inorder(root -> right, in); 27 } 28 };