Validate Binary Search Tree 验证二叉搜索树
题目描述:
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.
二叉搜索树定义:
二叉排序树或者是一棵空树,或者是具有下列性质的二叉树:
(1)若左子树不空,则左子树上所有结点的值均小于或等于它的根结点的值;
(2)若右子树不空,则右子树上所有结点的值均大于或等于它的根结点的值;
(3)左、右子树也分别为二叉排序树;
Example :
这里用中序遍历结果为:【1,3,4,6,7,8,10,13,14】,由此可见,用中序遍历搜索二叉树,遍历结果是从小到大排序的。
反例:
10
/ \
4 15
/ \ / \
2 5 6 17
由上图可得:15,6,17局部满足BST树,但是6<10,所以不是BST树,其中序遍历结果为:【2,4,5,10,6,15,17】,中序遍历结果不是从小到大排序的。
思路:我们可以根据其中序遍历的特点来进行判断是否合法。
/**
* 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) {
//方法一:采用中序递归遍历,求得遍历结果,放入容器vals中,然后比较大小
if (root==NULL)
return true;
vector<int> vals;
inorder(root, vals);
for (int i = 0; i < vals.size() - 1; ++i) {
if (vals[i] >= vals[i + 1])//中序从小到大
return false;
}
return true;
}
void inorder(TreeNode *root, vector<int> &vals) {//中序遍历
if (root==NULL) return;
inorder(root->left, vals);
vals.push_back(root->val);
inorder(root->right, vals);
//方法二:采用中序根左右的递归遍历,同时判断是否合法,中序遍历结果从小到大排序
/* TreeNode* prev = NULL;
return is_bst(root, prev);
}
bool is_bst(TreeNode* root, TreeNode*& prev){
if(root == NULL)
return true;
if(is_bst(root->left, prev)==NULL)
return false;
if(prev != NULL && prev->val >= root->val)
return false;
prev = root;
return is_bst(root->right, prev); */
}
};