LeetCode 98 Validate Binary Search Tree DFS

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;
    }
    
};


相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...