1,题目要求
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:
Example 2:
给定二叉树,确定它是否是有效的二叉搜索树(BST)。
假设BST定义如下:
节点的左子树仅包含键小于节点键的节点。
节点的右子树仅包含键大于节点键的节点。
左右子树也必须是二叉搜索树。
2,题目思路
对于这道题,判断一颗二叉树是否是是二叉搜索树。
而对于BST而言,其有个重要特性就是如果对其按照中序遍历的方法对该树进行遍历,我们可以得到一个从小到大的有序序列。
因此,在这道题的解决上,我们就结合中序的策略来对树进行遍历,并在遍历的过程中对相邻节点的值的大小进行判断即可。
而相邻相邻节点的值的判断,实现起来则是需要一个额外的变量pre来记录之前的节点的值。
在实现上,因为是常规的中序遍历的变种,因此,我们有递归和非递归两种方式。
3,代码实现
1,非递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
static const auto s = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
bool isValidBST(TreeNode* root) {
if(root == nullptr)
return true;
stack<TreeNode*> inorder;
TreeNode* pre = nullptr;
while(root!=nullptr || !inorder.empty()){
while(root != nullptr){
inorder.push(root);
root = root->left;
}
root = inorder.top();
inorder.pop();
if(pre!=nullptr && pre->val >= root->val)
return false;
pre = root;
root = root->right;
}
return true;
}
};
2,递归
class Solution {
public:
bool isValidBST(TreeNode* root) {
TreeNode* pre = nullptr;
return validHelper(root, pre);
}
private:
bool validHelper(TreeNode* node, TreeNode* &pre){
if(node == nullptr)
return true;
if(!validHelper(node->left, pre))
return false;
if(pre != nullptr && pre->val >= node->val)
return false;
pre = node;
return validHelper(node->right, pre);
}
};