Description
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.
Example 1
Input:
2
/ \
1 3
Output: true
Example 2
5
/ \
1 4
/ \
3 6
Output: false
Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value
is 5 but its right child's value is 4.
Solution 1(C++)
/**
* 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:
bool isValidBST(TreeNode* root) {
if(root == nullptr) return true;
if(!isValidBST(root->left)) return false;
if(pre != nullptr && pre->val >= root->val) return false;
pre = root;
return isValidBST(root->right);
}
private:
TreeNode* pre = nullptr;
};
Solution 2(C++)
class Solution {
public:
bool isValidBST(TreeNode* root) {
stack<TreeNode* > node_sofar;
int cur;
bool flag = true;
while(root || !node_sofar.empty()){
if(root){
node_sofar.push(root);
root = root->left;
}
else{
root = node_sofar.top();
node_sofar.pop();
if(flag) { cur = root->val; flag = false; }
else if(cur >= root->val) return false;
else cur = root->val;
root = root->right;
}
}
return true;
}
};
算法分析
解法一:
解法一使用递归的方法解决问题,用pre来储存遍历过的最大节点,可以理解为目前为止最右的节点。那么如发现pre的值大于root,就返回false。这个方法还是很有意思的,变形的中序遍历。
解法二:
由于题目要判断是不是标准二叉搜索树,所以自然可以通过中序遍历的方式来遍历一遍二叉搜索树,得到的应该是一个递增的数列,如果发现有逆序的出现,就返回false。值得注意的是,可以用最笨的方法,用一个vector < int >来储存二叉搜索树遍历过的数值,但是这会导致内存空间的消耗,所以用一个变量来保存上一个节点的数值,最开始我用INT_MIN,但是LeetCode增加了测试用例,这样是无法判断 [ INT _ MIN ] 这样的二叉树的。所以我用了解法二中的方法,增加了一个bool类型flag值,只在第一次访问这个数的时候对其进行更改。
程序分析
略。