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.
题目的意思:给一个二叉树,要求左子树比根节点小,右子树比根节点大,当树内所有节点都满足上述要求时,该二叉树为有效的二分搜索树。
解题思路:看了很多很多大佬都是用的递归,这样不用开辟新的空间,并且就树而言也没有什么重复的计算。可是我一开始最直接的思路就是:给树来一个中序遍历,这样我们就能得到如题目中的序列。再对序列进行遍历。一旦出现前者比后者大的情况即可返回false。
/**
* 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 == NULL) return true;
InOrder(root);
for(int i=0;i<v.size()-1;i++){
if(v[i+1] <= v[i])
return false;
}
return true;
}
void InOrder(TreeNode* root){
if(root->left != NULL) InOrder(root->left);
v.push_back(root->val);
if(root->right != NULL) InOrder(root->right);
}
private:
vector<int> v;
};