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.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"
.递归判断,递归时传入两个参数,一个是左界,一个是右界,节点的值必须在两个界的中间,同时在判断做子树和右子树时更新左右界。
1 /** 2 * Definition for binary tree 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 public: 12 bool check(TreeNode *node, int leftVal, int rightVal) 13 { 14 if (node == NULL) 15 return true; 16 17 return leftVal < node->val && node->val < rightVal && check(node->left, leftVal, node->val) && 18 check(node->right, node->val, rightVal); 19 } 20 21 bool isValidBST(TreeNode *root) { 22 // Start typing your C/C++ solution below 23 // DO NOT write int main() function 24 return check(root, INT_MIN, INT_MAX); 25 } 26 };