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.
链接:https://leetcode.com/problems/validate-binary-search-tree/
题解:判断是不是BST刚开始直接判断左孩子<root<右孩子,没有考虑左子树必须小于根节点的情况,实际上利用BST中序遍历是递增序列的性质判断,只需中序遍历然后用前序指针pre与当前节点root判断大小即可,刚开始定义pre用INT_MIN,结果题目数据出现比INT_MIN小或相等的数,实际上直接给pre初始化为null即可,然后访问pre->val时候判断pre是否为空再进行
注意!!!这里pre必须添加引用否则会报错因为这里的指针是需要移动的指针。
代码:
class Solution {
public:
bool isValidBST(TreeNode* root) {
TreeNode* prev = nullptr;
return validate(root, prev);
}
bool validate(TreeNode* node, TreeNode* &prev) {
if (node == nullptr) return true;
if (!validate(node->left, prev)) return false;
if (prev && prev->val >= node->val) return false;
prev = node;
return validate(node->right, prev);
}
};