Given the root
of a binary tree, determine if it is a valid binary search tree (BST).
A valid 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.
Solution
\(BST\) 满足对于中序遍历,得到的节点值为递增序列。所以先中序遍历以后,检查序列是否严格递增即可:
点击查看代码
/**
* DeFinition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
vector<int> node;
void dfs(TreeNode* root){
if(!root) return;
dfs(root->left); node.push_back(root->val); dfs(root->right);
}
public:
bool isValidBST(TreeNode* root) {
if(root==NULL) return true;
dfs(root);
int n = node.size();
for(int i=1;i<n;i++){
if(node[i-1]>=node[i])return false;
}
return true;
}
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。