98. 验证二叉搜索树
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 { 12 vector<int> nums; 13 void slove(TreeNode* root) 14 { 15 if(root == NULL) return; 16 slove(root->left); 17 nums.push_back(root->val); 18 slove(root->right); 19 } 20 public: 21 bool isValidBST(TreeNode* root) 22 { 23 if(root == NULL) return true; 24 slove(root); 25 int n = nums.size(); 26 for(int i = 1;i < n;i ++) 27 { 28 if(nums[i] <= nums[i - 1]) return false; 29 } 30 return true; 31 } 32 };
1 class Solution 2 { 3 public: 4 bool isValidBST(TreeNode* root) 5 { 6 return dfs(root,INT_MIN,INT_MAX); 7 } 8 9 bool dfs(TreeNode* root,long long minv,long long maxv) 10 { 11 if(!root) return true; 12 if(root->val < minv || root->val > maxv) return false; 13 14 //[负无穷,x - 1]和[x + 1,正无穷]中寻找 15 return dfs(root->left,minv,root->val - 1ll) && dfs(root->right,root->val + 1ll,maxv); 16 } 17 };
Mamba never out

浙公网安备 33010602011771号