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); } };