题目描述:
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.
Example 1:
Input: 2 / \ 1 3 Output: true
Example 2:
5 / \ 1 4 / \ 3 6 Output: false Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value is 5 but its right child's value is 4.
算法实现:
直接上算法,递归或者中序遍历的方式,注释写的比较清楚
//想法,中序遍历,如果为升序则true,否则判错
//实际上严格意义上讲,BST要求left <= root < right,即一个数如果和根节点相同,那么只能在左侧,所以严格意义上说是能用中序遍历的,如两个相同数字1组成的树,一个1为1的左子树,一个1为1的右子树,这两种情况中序遍历相同,但是不都是true的
/**
* 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 isValidBST(TreeNode* root) {
return isValid(root,LONG_MIN,LONG_MAX);
}
bool isValid(TreeNode* root, long lbound, long ubound) {
if(root == NULL) return true;
//这个问题具体还是要求左<中<右来实现的,没有严格按照BST的定义来实现;若想严格按照定义,只需要将下面一行的>=中的=去掉即可
if(root -> val <= lbound || root -> val >= ubound)return false;
return isValid(root -> left,lbound,root -> val) && isValid(root -> right, root -> val,ubound);
}
};