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.
思路:
仍然是树的深度优先搜索。这里要注意的是,不能仅仅和父结点的值比较,还必须和上面所有的结点进行比较。
题解:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<pair<int, char>> history;
bool isValidBST(TreeNode *node) {
if (node == nullptr)
return true;
// check if I am ok with all the parents
for(auto& h : history)
if (h.second == 'R')
{
// i am at the right subtree
if (node->val <= h.first)
return false;
}
else
{
// i am at the left subtree
if (node->val >= h.first)
return false;
}
bool leftok = true;
history.push_back(make_pair(node->val, 'L'));
leftok = isValidBST(node->left);
bool rightok = true;
history.back().second = 'R';
rightok = isValidBST(node->right);
history.pop_back();
return leftok && rightok;
}
};