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.
思路:复习一下中序遍历,但其实可以降低一下空间复杂度。
class Solution {
public:
bool isValidBST(TreeNode* root) {
if (!root || (!root->left&&!root->right))
return true;
vector<int> res;
inOrder(root, res);
for (int i = 1; i < res.size();i++)
if (res[i] <= res[i - 1])
return false;
return true;
}
void inOrder(TreeNode* root, vector<int> &res){
stack<TreeNode*> stk;
TreeNode *p = root;
while (p || !stk.empty()){
while (p){
stk.push(p);
p = p->left;
}
p = stk.top();
stk.pop();
res.push_back(p->val);
p = p->right;
}
}
};