LintCode-95: Validate Binary Search Tree (BST经典题)

超大规模AI集群跨数据中心互联:Scale-Across技术实现与部署实践 分布式系统通过将计算任务分散到多个节点协同执行,实现算力的横向扩展。其核心原理在于网络通信、数据同步和资源调度机制的技术协同。在AI基础设施领域,分布式架构能有效突破单数据中心算力瓶颈,支撑万亿参数大模型训练。特别是面对长距离传输时延和带宽稳定性挑战,需要采用RDMA、确定性网络等关键技术。Scale-Across作为分布式系统的高级形态,通过跨地域多数据中心互联,构建逻辑统一的AI算力池,为超大规模AI训练和全球推理服务提供核心支撑。本文聚焦AI集群跨数据中心互联的技术路径,涵盖全栈优化、网络自治等实践方 阅读详情
  1. Validate Binary Search Tree

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.
A single node tree is a BST
Example
Example 1:

Input: {-1}
Output:true
Explanation:
For the following binary tree(only one node):
-1
This is a binary search tree.
Example 2:

Input: {2,1,4,#,#,3,5}
Output: true
For the following binary tree:
2
/
1 4
/
3 5
This is a binary search tree.

解法1:
首先要注意的是BST的定义:

  1. root的值要大于所有左子树的节点的值,小于所有右子树节点的值。所以不能单单和左子节点与右子节点比较。
    像下面这个代码就不会通过这个测试用例:
    10,5,15,#,#,6,20
    因为该例并非BST (10>6)。
    bool isValidBST(TreeNode * root) {
        if (!root)
            return true;
        
        if (root && !root->left && !root->right) 
            return true;
        
        return isValidBST(root->left) && 
                isValidBST(root->right) && 
               (root->left ? root->val > root->left->val : true) &&
               (root->right ? root->val < root->right->val : true);
    }
  1. helper()函数会返回该root所代表的子树里面的最大值和最小值。左右子树的最大值和最小值都要考虑。
    考虑
  2. min, max 还要考虑root本身的值。
  3. 下面链接有两个version值得好好研究。下次学习。
    https://www.jiuzhang.com/solution/validate-binary-search-tree/#tag-highlight-lang-cpp

另外,这个链接关于LCA的讨论好像很不错,下次参考。
https://www.hrwhisper.me/algorithm-lowest-common-ancestor-of-a-binary-tree/

代码如下:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: The root of binary tree.
     * @return: True if the binary tree is BST, or false
     */
    bool isValidBST(TreeNode * root) {
        if (!root)
            return true;
        
        if (root && !root->left && !root->right) 
            return true;
        
        ReturnType leftRet = helper(root->left);
        ReturnType rightRet = helper(root->right);
        
        return isValidBST(root->left) && 
               isValidBST(root->right) && 
               (root->left ? root->val > leftRet.max : true) &&
               (root->right ? root->val < rightRet.min : true);
    }
    
private:
    struct ReturnType {
        int max;
        int min;
        ReturnType(int a=INT_MIN, int b=INT_MAX) : max(a), min(b) {}
    };
    
    ReturnType helper(TreeNode* root) {
        ReturnType ret;
        
        if (!root) 
            return ret;
        
        if (root && !root->left && !root->right) 
            return ReturnType(root->val, root->val);
            
        ReturnType leftRet = helper(root->left);
        ReturnType rightRet= helper(root->right);
        
        ret.max = max(root->val, max(ret.max, max(leftRet.max, rightRet.max)));
        ret.min = min(root->val, min(ret.min, min(leftRet.min, rightRet.min)));
        
        return ret;
    }
};

这个代码效率好像非常非常低,应该是做了很多无用计算。重新改写了一下,这个代码效率高很多。

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: The root of binary tree.
     * @return: True if the binary tree is BST, or false
     */
    bool isValidBST(TreeNode * root) {
        if (!root)
            return true;
        
        if (root && !root->left && !root->right) 
            return true;
        
        ReturnType ret = helper(root, LONG_MIN, LONG_MAX);
        
        if (ret.valid)
            return true;
        else
            return false;
    }
    
private:
    struct ReturnType {
        long min;
        long max;
        bool valid;
        ReturnType(long a=LONG_MIN, long b=LONG_MAX, bool c=true) : min(a), max(b), valid(c) {}
    };
    
    ReturnType helper(TreeNode* root, long min, long max) {
        ReturnType ret;
        
        if (!root) 
            return ret;
        
        ReturnType leftRet = helper(root->left, min, (long)root->val);
        ReturnType rightRet= helper(root->right, (long)root->val, max);
        
        if (!leftRet.valid || !rightRet.valid || root->val <= min || root->val >= max)
            return ReturnType(min, max, false);
        
        return ReturnType(min, max, true);
    }
};

解法3:
在构造一个BST时,一个左节点的值介于父亲子树的最小值和父亲值之间,一个右节点的值介于父亲值和父亲子树的最大值之间,才能继续向下构造。
更新:
每个节点都必须大于其左子树的最大值,小于其右子树的最小值,才算合格。

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: The root of binary tree.
     * @return: True if the binary tree is BST, or false
     */
    bool isValidBST(TreeNode * root) {
        return helper(root, LONG_MIN, LONG_MAX);
    }
    
private:
    bool helper(TreeNode * root, long leftMax, long rightMin) {
        if (!root) return true;
        if (root->val <= leftMax|| root->val >= rightMin) return false;
        return helper(root->left, leftMax, root->val) && helper(root->right, root->val, rightMin);
        
    }
};

解法4:利用BST的InOrder遍历是递增序列这个特性。


class Solution {
public:
    /**
     * @param root: The root of binary tree.
     * @return: True if the binary tree is BST, or false
     */
    bool isValidBST(TreeNode * root) {
        if (!root) return true;
        inOrderTraversal(root);
        int len = inOrderRes.size();
        for (int i = 1; i < len; i++) {
            if (inOrderRes[i] <= inOrderRes[i - 1]) return false;
        }
        return true;        
    }
private:
    vector<int> inOrderRes;
    void inOrderTraversal(TreeNode *root) {
        if (!root) return;
        inOrderTraversal(root->left);
        inOrderRes.push_back(root->val);
        inOrderTraversal(root->right);
    }
};

代码同步在
https://github.com/luqian2017/Algorithm/

非递归的版本如下:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: The root of binary tree.
     * @return: True if the binary tree is BST, or false
     */
    bool isValidBST(TreeNode * root) {
        stack<TreeNode *> stk;
        TreeNode *pre = nullptr;
        while (!stk.empty() || root) {
            while(root) {
                stk.push(root);
                root = root->left;
            }
            root = stk.top();
            stk.pop();
            if (pre && pre->val >= root->val) return false;
            pre = root;
            root = root->right;
        }
        return true;
    }
};

5刷:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

struct ResultType {
    bool isValid;
    long long maxVal;
    long long minVal;
    ResultType(bool isV, long long maxV, long long minV) : isValid(isV), maxVal(maxV), minVal(minV) {}
};

class Solution {
public:
    /**
     * @param root: The root of binary tree.
     * @return: True if the binary tree is BST, or false
     */
    bool isValidBST(TreeNode * root) {
        return helper(root).isValid;
    }
private:
    ResultType helper(TreeNode *root) {
        if (!root) {
            return ResultType(true, LLONG_MIN, LLONG_MAX);//注意不能用INT_MIN和INT_MAX,不然如果节点值就是INT_MIN或INT_MAX会出错。
        }
        if (!root->left && !root->right) {
            return ResultType(true, root->val, root->val);
        }
        ResultType left = helper(root->left);
        if (!left.isValid) {
            return ResultType(false, 0, 0);
        }
        ResultType right = helper(root->right);
        if (!right.isValid) {
            return ResultType(false, 0, 0);
        }
        if (root->val > left.maxVal && root->val < right.minVal) {
            return ResultType(true, root->right ? right.maxVal : root->val, root->left ? left.minVal : root->val);
        } //注意这里要加判断root->right和root->left是否存在的情况,不然的话,如果不存在,那么right.maxVal和left.minVal会用到LLONG_MIN和LLONG_MAX
        return ResultType(false, 0, 0);
    }    
};

6刷:

/**
 * 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:
    bool isValidBST(TreeNode* root) {
        return helper(root, NULL, NULL);
    }
private:
    bool helper(TreeNode *root, TreeNode *minNode, TreeNode *maxNode) {
        if (!root) return true;
        if (minNode) {
            if (minNode->val >= root->val) return false;
        }
        if (maxNode) {
            if (maxNode->val <= root->val) return false;
        }
            
        return helper(root->left, minNode, root) && helper(root->right, root, maxNode);
    }
};

8刷:

/**
 * 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:
    bool isValidBST(TreeNode* root) {
        if (!root) return true;
        TreeNode *visited = new TreeNode(-1);
        long long preV = (long long)INT_MIN - 1;
        goLeft(root);        
        while (!stk.empty()) {
            TreeNode *topNode = stk.top();
            if ((!topNode->left || topNode->left == visited) && topNode->right != visited) {
                //inorder code here
                if ((long long)topNode->val <= preV) return false;
                preV = (long long)topNode->val;
                goLeft(topNode->right);
            }
            if (!topNode->right || topNode->right == visited) {
                //postorder code here
                visited = topNode;
                stk.pop();
            }
         }
         return true;
    }
private:
    stack<TreeNode *> stk;
    void goLeft(TreeNode *root) {
        while (root) {
            //preorder code here
            stk.push(root);
            root = root->left;
        }
        return;
    }
};
Windows下用Docker快速搭建SearXNG私有搜索引擎(附Dify集成配置) 本文详细介绍了在Windows环境下使用Docker快速搭建SearXNG私有搜索引擎的完整流程,包括环境准备、容器化部署、安全配置优化以及与Dify平台的深度集成方法。通过分步指导和实用配置示例,帮助开发者构建兼具隐私保护和AI增强能力的本地化搜索解决方案,特别适合需要定制化搜索服务的应用场景。 阅读详情

相关推荐

创建XCP的CanApe工程

创建XCP的CanApe工程

weixin_44173919的博客 2889

LeetCode 98. Validate Binary Search Tree(判断是否为二叉搜索树,C++,python)

98. Validate Binary Search Tree 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 ...

ha_ha_ha233的博客 416

Arco Design Pro PC端商家后台框架 | Axure高保真原型库

摘要:本Axure原型设计方案基于字节跳动ArcoDesignPro规范,提供企业级后台快速搭建方案。包含动态表格、表单验证等核心组件,采用中继器驱动设计,支持响应式布局。方案覆盖80%后台常用交互,可节省60%原型制作时间,配套完整设计文档和组件库,实现原型到开发的高效衔接。特别适用于电商、SaaS等后台系统开发,支持权限管理、数据分析等场景,显著提升团队协作效率。

招风的黑耳优快云 3971

98. Validate Binary Search Tree

Given the of a binary tree, determine if it is a valid binary search tree (BST).A valid BST is defined as follows:subtreeExample 1: Input: root = [2,1,3] Output: true Example 2: Input: root = [5,1,4,null,null,3,6] Output: false Explanation: The root nod

2301_80161204的博客 950

仿真每日一练 | 有限元模态分析详解

结构的振动一直是工业领域产品分析的重点,在振动的仿真分析中,模态分析是其最基本的分析类型,通过研究结构的固有频率和振型对产品的设计提供指导。2.2、在interaction模块,通过special->Spring,在各点之间分别创建弹簧单元,弹簧刚度为1000。2.1、在interaction模块,创建两个RP点,与两侧RP点各间隔100大小,如图3所示;其中M、K、C均为n*n的矩阵,s、x、v为n*1的矢量,n为系统自由度数量。3、在Assembly模块创建装配体,两点之间的距离为100,如图2所示;

ansysxuexizhe的博客 1655

Zephyr 开发必备技能:一文搞懂 west manifest

本文深入解析Zephyr项目的westmanifest工具与Manifest文件管理,从基础概念到高级应用。文章首先介绍westmanifest作为Zephyr模块化架构的核心工具,负责管理west.yml文件中的模块信息、Git地址及版本控制。随后详细讲解Manifest文件的基本结构、字段含义,以及westmanifest子命令的使用方法,包括查看内容、冻结版本、验证文件等操作。文章还探讨了Manifest的导入继承机制和在团队协作中的版本管理策略,并给出常见问题排查技巧。最后强调Manifest文件作

hemoparrot的专栏 1255

98. Validate Binary Search Tree(验证二叉搜索树)

98. Validate Binary Search Tree 如题验证一个树是否是搜索树,搜索树的性质在这里就不说了,那首先想到一个简单的就是递归中序遍历,如果出来的这个数组不是有序的,那么这棵树必然不是一个搜索树,这是一个做法,但是如果门不使用额外空间,并且采用递归的方式判断一棵树是否是搜索树的条件是什么,在从root节点递归到左子树中时候,左子树中最大的节点,也就是左子树中最右边的节点需要...

asd994144293的博客 217

No Target Connected 错误时的一种情况

STM32的SWD烧录模式No Target Connected 错误的一种情况 STM32的SWD烧录模式No Target Connected 错误时的一种处理情况 这是我第一次烧板子的时候遇到的问题,在给板子download的时候出现了“No Target Connected”的错误,这里讲一种解决方法。不一定适用于全部状况,但是可以作为一种纠错方法。 打开 Options for Target… 1.首先点击Options for Target…这个像魔棒一样的按键打开,会出现这个页面 2.点击

Logan_CodeGou的博客 1万+

LeetCode刷题-98——Validate Binary Search Tree(验证搜索二叉树)

链接:点击打开链接题目:给定一个二叉树,判断其是否是一个有效的二叉搜索树。一个二叉搜索树具有如下特征:节点的左子树只包含小于当前节点的数。节点的右子树只包含大于当前节点的数。所有左子树和右子树自身必须也是二叉搜索树。Example:示例1输入: 2 / \ 1 3 输出: true示例2 5 / \ 1 4   / \   3 6 Outpu...

Fan2g 1061

MySQL 高可用与集群技术深度解析

高可用性(High Availability,HA)是指系统在较长时间内持续提供服务的能力,通常以系统正常运行时间占总时间的百分比(如 “99.99% 可用性”)来衡量。对于数据库系统而言,高可用性目标是通过冗余设计、故障自动检测与恢复、负载均衡等技术手段,最大限度地减少因硬件故障、软件错误、网络问题等导致的服务中断,确保数据的高可靠性和业务的连续性。

加入“Super Entity”,与全能开发团队共探AI智能体与数字人项目,开启前沿技术之旅。 1501

GStreamer Plugin之Gst-nvdewarper

支持三种投影类型 NVDS_META_SURFACE_FISH_PUSHBROOM, NVDS_META_SURFACE_FISH_VERTCYL 和NVDS_META_SURFACE_PERSPECTIVE_PERSPECTIVE。关于每个平面的NvDewarperSurfaceMeta参数(projection_type, surface_index, and source_id)以及内存中有效的矫正平面(num_filled_surfaces)包含RGBA格式的一帧的缓存。矫正后的RGBA格式。

pvmsmfchcs的博客 366

Validate Binary Search Tree

二叉树中序遍历一遍,看是不是严格

angelewings的专栏 385

SAP 系统间信任关系配置全攻略:从 SM59 到 SMT1 的实践与风险控制

本文介绍了在SAP系统间配置信任关系的详细流程与最佳实践。文章以SAP Gateway与后端系统架构为场景,从SM59创建RFC目的地开始,到SMT1建立信任关系,再到授权对象S_RFCACL的配置,提供了完整的操作指南。重点包括:使用标准命名规范创建专用RFC连接、通过向导完成系统间信任登记、严格控制S_RFCACL授权范围等。文中还分享了真实项目案例、可复用的检查清单以及常见问题的排查思路,帮助用户实现稳定可靠的跨系统无密码调用,同时确保安全性。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 321

[Lintcode]95. Validate Binary Search Tree/[Leetcode]98. Validate Binary Search Tree

95. Validate Binary Search Tree/98. Validate Binary Search Tree 本题难度: Easy Topic: Binary Tree Description Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is de...

weixin_30851409的博客 126

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

lintcode validate-binary-search-tree 验证二叉查找树

问题描述lintcode笔记 代码1是用到中序遍历,要求中序遍历是严格的增序。用到了辅助空间。 代码2是leetcode上面的解法,用到了prev指针记录前一个节点,省下了辅助空间,而且要注意prev传进去还应该是引用。 代码1/** * Definition of TreeNode: * class TreeNode { * public: * int val; * Tr

stevewong的专栏 1043

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

Lintcode95 Validate Binary Search Tree solution 题解

【题目描述】 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 keysless thanthe node's

Winnielyn623的博客 484

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

LintCode 95. Validate Binary Search Tree

题目 思路 拆解子问题。 找到左子树和右子树中最大值和最小值,和根节点进行比较。 代码 """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ cl...

SparkSnail 206

LintCode-95: Validate Binary Search Tree

这题有两种解法: 解法1:利用binary search tree &amp;lt;=&amp;gt; 中序遍历为升序序列 这个充要条件。 注意这题条件好像认为bst不存在重复元素,但实际上是可以重复的,而且重复元素(根和子节点值一样的话),子节点放在左边。 代码如下: /** * Definition of TreeNode: * class TreeNode { * public: * ...

roufoo的博客 220

Lintcode 95. Validate Binary Search Tree (Medium) (Python)

Validate Binary Search Tree Description: 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 node...

DY的博客 203

*lintcode95- Validate Binary Search Tree- medium

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 keysless thanthe node's key. Th...

weixin_30550081的博客 111

Validate Binary Search Tree——LeetCode

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 keysless thanthe node's key...

141

[LeetCode] 98. Validate Binary Search Tree

原题链接:https://leetcode.com/problems/validate-binary-search-tree/ 1. 题目介绍 Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree o...

Ber03的博客 227

Validate Binary Search Tree 验证二叉搜索树

给定一个二叉树,判断其是否是一个有效的二叉搜索树。一个二叉搜索树具有如下特征:节点的左子树只包含小于当前节点的数。节点的右子树只包含大于当前节点的数。所有左子树和右子树自身必须也是二叉搜索树。示例 1:输入: 2 / \ 1 3 输出: true 示例 2:输入: 5 / \ 1 4   / \   3 6 输出: false 解释: 输入...

qq_26410101的博客 286

98.Validate Binary Search Tree

题目描述(中等难度) 输入一个树,判断该树是否是合法二分查找树,95题做过生成二分查找树。二分查找树定义如下: 若任意节点的左子树不空,则左子树上所有节点的值均小于它的根节点的值; 若任意节点的右子树不空,则右子树上所有节点的值均大于它的根节点的值; 任意节点的左、右子树也分别为二叉查找树; 没有键值相等的节点。 解法一 递归 要解决这道题首先我们要了解二叉搜索树有什么性质可以给我们利用,由题目给出的信息我们可以知道:如果该二叉树的左子树不为空,则左子树上所有节点的值均小于它的根节点的值; 若它的右子

猫敷雪 399

算法系列——验证二叉搜索树(Validate Binary Search Tree)

题目 给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。 有效 二叉搜索树定义如下: 节点的左子树只包含 小于 当前节点的数。 节点的右子树只包含 大于 当前节点的数。 所有左子树和右子树自身必须也是二叉搜索树。 解答 中序遍历版本,如果发现当前结点值>= 前驱结点值,是非法的。 class Solution { private long prev=Long.MIN_VALUE; private boolean result=true; public

BridgeGeorge 697

【LeetCode & 剑指offer刷题】树题13:Validate Binary Search Tree

【LeetCode &amp; 剑指offer刷题】树题13:Validate Binary Search Tree 【LeetCode &amp; 剑指offer 刷题笔记】目录(持续更新中...) Validate Binary Search Tree Validate Binary Search Tree Given a binar...

技术改变世界 523
上一篇: LintCode-578: Lowest Common Ancestor III
下一篇: LintCode-901. Closest Binary Search Tree Value II
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值