给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/validate-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法1:递归
二叉搜索树的性质:二叉搜索树的中序遍历必然是一个递增数组
由以上性质我们直接中序遍历二叉搜索树,然后判断是不是递增数组就可知道是否符合要求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
class Solution { private: vector<int> res; public: bool isValidBST(TreeNode* root) { midDFS(root); int i; for(i=1;i<res.size();i++) { if(res[i-1]>=res[i]) return false; } return true; } void midDFS(TreeNode *root) { if(root!=NULL) { midDFS(root->left); res.push_back(root->val); midDFS(root->right); } } };
|