版权声明:本文为博主原创文章,未经博主许可允许转载。 https://blog.csdn.net/qq_29600137/article/details/89297349
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 thanthe 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.
题目大意:
问二叉树是否可以满足左边都小于当前节点,右边都大于当前节点。注意存在重复数据。
解题思路:
二叉树中序遍历,判断数组是否为升序序列。
/**
* 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 {
private:
vector<int> ans;
void search(TreeNode* tmp){
if(tmp->left == NULL && tmp->right == NULL){
ans.push_back(tmp->val);
return;
}
if(tmp->left != NULL){
search(tmp->left);
}
ans.push_back(tmp->val);
if(tmp ->right != NULL){
search(tmp->right);
}
}
public:
bool isValidBST(TreeNode* root) {
if(root==NULL){
return true;
}
search(root);
for(int i =1;i<ans.size();i++){
if(ans[i-1] >= ans[i]){
return false;
}
}
return true;
}
};