题目: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. 题目源自于leetcode。
思路一:一个二叉树,它是二叉查找树的必要条件是中序遍历序列必须是单增序列。因此,我的方法就是判断中序遍历序列是否是递增的。我只是想判定是否是自增,因为没有必要列出整个中序遍历,只需要在中序序列添加新元素的时候判断一下是否比上一个更大即可。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode *root) {
int pre = INT_MAX; //最初的pre设为一个特殊值
return fun(root, pre);
}
bool fun(TreeNode *root, int &pre) //只需要一个int来保存中序遍历序列的上一个数
{
if(root != NULL)
{
bool left = fun(root->left, pre);
if(pre != INT_MAX && pre >= root->val) //判断新增的值是否是满足增序
return false;
pre = root->val; //更新序列最后一个数
bool right = fun(root->right, pre);
return left && right; //返回左右子树的综合状态
}
else
return true; //到达空树直接返回true
}
};
本方法中的第二个参数pre是用于记录序列的上一个数。当然,也可以用一个全局变量来记录。
思路二:依据二叉排序树的定义递归进行。对于一个二叉排序树,左子树中所有数都比其小,右子树中所有数都比其大。递归时越往深处走,其范围限定的越是小。
class Solution {
public:
bool isValidBST(TreeNode *root) {
return isValid(root, INT_MIN, INT_MAX);
}
bool isValid(TreeNode *root, int low, int high)
{
if(root == NULL)
return true;
return root->val > low && root->val < high
&& isValid(root->left, low, root->val)
&& isValid(root->right, root->val, high);
}
};