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.
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
Subscribe to see which companies asked this question
分析:
bst的中序遍历是非减序列。
代码:
/**
* 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:
void ordtravel(TreeNode* root,vector<int>& v1)
{
if(root==NULL){ return ;}
if(root->left) ordtravel(root->left,v1);
v1.push_back(root->val);
if(root->right) ordtravel(root->right,v1);
}
bool isValidBST(TreeNode* root) {
if(root==NULL) return true;
vector<int> v1;
ordtravel(root,v1);
for(int i=1;i<v1.size();++i)
{
if(v1[i]<=v1[i-1]) return false;
}
return true;
}
};