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

ArcGIS 10.2.2自带Python 2.7.5环境配置全攻略:从pip安装到gdal、arcpy调用 本文详细指导如何在ArcGIS 10.2.2自带的Python 2.7.5环境中进行高效配置。核心内容包括安装pip包管理器、部署gdal等关键地理数据处理库,并确保arcpy模块的无缝调用。通过解决路径配置与PyCharm集成问题,帮助用户在此经典环境中构建稳定、兼容的地理信息自动化工作流,有效连接ArcGIS桌面功能与Python脚本编程。 阅读详情
  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;
    }
};
Android 14.0 SystemUI下拉通知栏通知去掉长按事件 在14.0的系统rom产品定制化开发中,在systemui模块中关于下拉状态栏这块也是非常重要的部分,最近在关于systemui下拉通知栏的每条通知部分 要求去掉通知栏通知的长按事件,不需要长按功能,所以就需要分析下关于长按事件是在哪里注册的,然后去掉就可以了,接下来分析实现 相关功能 阅读详情

相关推荐

从飞机翼型仿真到燃烧模拟:Fluent多物理场耦合的3种实战策略

本文深入探讨了Fluent在多物理场耦合仿真中的三种实战策略,涵盖可压缩流动与燃烧耦合、湍流模型选择及网格策略,以及顺序耦合、强耦合和混合耦合方法。通过具体案例和工程实践,帮助中高级用户提升仿真精度和效率,适用于航空航天和能源化工等领域。

aa123的博客 1010

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的博客 419

UE5 StateTree实战:用分层状态机重构你的AI行为逻辑(附蓝图配置避坑点)

本文详细介绍了UE5中StateTree分层状态机的实战应用,帮助开发者重构AI行为逻辑。通过核心概念解析、迁移策略、高级技巧和避坑指南,展示了StateTree在灵活性、可维护性和并行处理方面的优势,特别适合复杂AI行为的开发与优化。

weixin_42558257的博客 262

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的博客 953

Qoder保姆级教程:从安装到多模型接入,全面平替Codex

AI编程正从命令行工具走向AI原生IDE,自然语言驱动Agent生成项目文件、多文件联动修改,已成为开发者提效的新范式。传统CLI工具如Codex虽能力强大,但环境配置复杂、模型绑定封闭,让不少用户望而却步。Qoder作为AI原生IDE,以低门槛、可视化、多模型自由切换为特点,将Agent的文件操作、运行调试、画布预览集成在编辑器内,让“从0写网站”这类任务变得直观可控。文章从概念、原理、技术价值与应用场景切入,围绕Codex平替这一需求,系统讲解Qoder的安装选型、项目实操、接入DeepSeek等第三方

weixin_32377497的博客 363

Unreal5从入门到精通之初学者碰到解决不了的问题怎么办?

在学习Unreal的过程中,你曾陷入困境了吗?对于我来说,这种情况发生得比我愿意承认的要多得多。幸运的是,除了一般地在网上搜索之外,还有很多地方可以获得虚幻引擎的帮助。

TxNet 994

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

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

asd994144293的博客 218

C# Winform使用Monaco打造代码编辑器

本文介绍了如何在Winform项目中集成Monaco代码编辑器。通过NuGet安装WebView2控件,创建monaco-editor.html文件加载编辑器,并实现与C#代码的交互。关键步骤包括:初始化WebView2环境、配置Monaco编辑器参数、设置代码变更监听事件以及处理C#与JavaScript之间的通信。注意事项提示了依赖库安装问题的解决方法。该方案实现了功能完整的代码编辑器,支持代码自动保存和实时显示功能。

遇见--专栏 355

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

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

Fan2g 1061

图像紫边消除(depurple)

对图像紫边形成原因、消除方法进行了介绍。

沧海一升的博客 7582

学Simulink——基于电能质量治理的场景实例:静止无功发生器(SVG)与并网逆变器的结合

本文详细介绍了基于Simulink的SVG与光伏并网逆变器联合仿真建模方法。系统包含光伏单元、SVG主电路、控制策略(无功检测+双闭环控制)等模块,通过ip-iq法实现动态无功补偿。仿真结果表明,SVG能快速响应负载变化,将功率因数提升至0.98以上,有效稳定母线电压。该方案为新能源并网系统提供了有功/无功协同控制解决方案,具有10ms级响应速度和±5kvar补偿能力。文章提供了完整的建模流程、控制算法实现和结果分析,可作为电力电子与电能质量治理领域的实践指导。

amy_mhd的博客 176

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...

142

【ESP32摄像头开发实例】-视频流接入Home Assistant

在这个项目中,我们将使用ESP32-CAM板构建一个IP监控摄像头。ESP32摄像头将托管一个视频流媒体网络服务器,您可以使用网络中的任何设备进行访问。

视觉与物联智能 808

[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

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

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

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

stevewong的专栏 1050

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

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的博客 485

OV9734 DATASHEET,完整规格书

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

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 207

LintCode-95: Validate Binary Search Tree

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

roufoo的博客 221

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的博客 114

[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的博客 228

Validate Binary Search Tree

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

angelewings的专栏 385

Validate Binary Search Tree 验证二叉搜索树

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

qq_26410101的博客 288

98.Validate Binary Search Tree

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

猫敷雪 400

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

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

BridgeGeorge 697

[leetcode]Validate Binary Search Tree (判断有效二叉搜索树 C语言实现)

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 t

道虽迩,不行不至;事虽小,不为不成 1649
上一篇: 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、付费专栏及课程。

余额充值
⌂ 换网址