leetcode日记85验证二叉搜索树
目录
leetcode日记(85)验证二叉搜索树
不难,有两种解法(看答案才想到中序遍历)。
我用的是普通递归,和上一题差不多,规定min和max,每次遍历缩小范围:
/**
- Definition for a binary tree node.
- struct TreeNode {
- int val;
- TreeNode *left;
- TreeNode *right;
- TreeNode() : val(0), left(nullptr), right(nullptr) {}
- TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
- TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
- }; / class Solution { public: bool Vaild(TreeNode root,long int min,long int max){ bool b=1; if(root->val>=max||root->val<=min) return 0; if(root->left!=NULL){ b=b&Vaild(root->left,min,root->val); } if(b==0) return 0; if(root->right!=NULL){ b=b&Vaild(root->right,root->val,max); } return b; } bool isValidBST(TreeNode* root) { long int min=-2147483649; long int max=2147483648; return Vaild(root,min,max); } }; 也可以用中序遍历的方法。