98.Validate Binary Search Tree(二查搜索树)
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
思想其实很简单,但是我为啥就是想不到呢?????!!!!!
递归判断,递归时传入两个参数,一个是左界,一个是右界,节点的值必须在两个界的中间,同时在判断做子树和右子树时更新左右界。
需要考虑结点取INT_MAX 或者INT_MIN的情况,
相应的改成long long 以及 LONG_LONG_MAX 和LONG_LONG_MIN后提交通过。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool check(TreeNode *node, long long leftVal, long long rightVal) { if (node == NULL) return true; return leftVal < node->val && node->val < rightVal && check(node->left, leftVal, node->val) && check(node->right, node->val, rightVal); } bool isValidBST(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function return check(root, LONG_LONG_MIN , LONG_LONG_MAX); } };
2)更好的方法,采用搜索二叉树常用的中序遍历是有序的这个性质,注意代码实现栈的使用,如何防止反复遍历(代码可以套模式的)
/** * 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 isValidBST(TreeNode* root) { if(root==nullptr) {return true;} stack<TreeNode*> stk; long long inorder = (long long)INT_MIN - 1; while(!stk.empty() || root!=nullptr) { while(root!=nullptr) { stk.push(root); root = root->left; } root = stk.top(); stk.pop(); if(root->val <= inorder) {return false;} inorder = root->val; root = root->right; } return true; } };