首页 > 其他分享 >98. 验证二叉搜索树

98. 验证二叉搜索树

时间:2022-08-25 22:14:03浏览次数:79  
标签:node right TreeNode 验证 二叉 98 root 节点 left

98. 验证二叉搜索树

给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。

有效 二叉搜索树定义如下:

  • 节点的左子树只包含 小于 当前节点的数。
  • 节点的右子树只包含 大于 当前节点的数。
  • 所有左子树和右子树自身必须也是二叉搜索树。

 

示例 1:

输入:root = [2,1,3]
输出:true

示例 2:

输入:root = [5,1,4,null,null,3,6]
输出:false
解释:根节点的值是 5 ,但是右子节点的值是 4 。

 

提示:

  • 树中节点数目范围在[1, 104]
  • -231 <= Node.val <= 231 - 1

 

解析:

为啥通过率这么低?

看看中序遍历是否是递增序列就可以

/**
 * 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 {
public:
    
    void dfs(TreeNode* root, vector<int>& node)
    {
        if(root == nullptr)
            return;
        dfs(root->left, node);
        node.push_back(root->val);
        dfs(root->right, node);
    }

    bool isValidBST(TreeNode* root) {
        vector<int> node;
        dfs(root, node);
        bool flag = 0;
        for(int i = 1; i < node.size(); i++)
        {
            if(node[i] <= node[i - 1])
            {
                flag = 1;
                break;
            }
        }
        return !flag;

    }
};

 

标签:node,right,TreeNode,验证,二叉,98,root,节点,left
From: https://www.cnblogs.com/WTSRUVF/p/16625895.html

相关文章

  • leetcode144:二叉树的前序遍历
    packagecom.mxnet;importjava.util.ArrayList;importjava.util.List;publicclassSolution144{publicstaticvoidmain(String[]args){}/**......
  • leetcode226-翻转二叉树
    翻转二叉树递归classSolution{publicTreeNodeinvertTree(TreeNoderoot){if(root==null)returnroot;TreeNodel=invertTree(roo......
  • leetcode222-完全二叉树的节点个数
    完全二叉树的节点个数递归classSolution{publicintcountNodes(TreeNoderoot){if(root==null)return0;returncountNodes(root.le......
  • element ui表单 对象 数组验证
     //表单参数   form:{    jobName:"",    jobNo:"",    produceList:[     {      orderNum:"", ......
  • PHP代码连接Redis,含Redis密码验证、指定某一Redis数据库
    <?php$redis=newRedis();$redis->connect('127.0.0.1',6379);//连接Redis$redis->auth('mypasswords123sdfeak');//密码验证$redis->select(2);//选择......
  • 平衡二叉树(AVL)的实现
    平衡二叉树概念平衡二叉排序树(BalancedBinaryTree),因由前苏联数学家Adelson-Velskii和Landis于1962年首先提出的,所以又称为AVL树。平衡二叉树是一种特殊的二叉排序......
  • 798 差分
    includeusingnamespacestd;constintN=2000;inta[N][N],b[N][N];intmain(){intn,m,q;cin>>n>>m>>q;for(inti=1;i<=n;i++){for(intj......
  • 二叉树的结构
    https://www.acwing.com/problem/content/description/4274/#include<bits/stdc++.h>#include<string.h>usingnamespacestd;constintN=1010;intpost[N],in[N......
  • 判断是不是平衡二叉树
    staticintflag=0;publicbooleanisBalanced(TreeNoderoot){flag=0;travel12(root);if(flag==1){returnfalse;......
  • 验证码和前台数据处理结果
    验证码和前台数据处理结果RegistUserServlet类:@WebServlet("/registUserServlet")publicclassRegistUserServletextendsHttpServlet{protectedvoiddoPost(......