zoukankan      html  css  js  c++  java
  • LeetCode(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 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.
    confused what “{1,#,2,3}” means? > read more on how binary tree is serialized on OJ.

    OJ’s Binary Tree Serialization:
    The serialization of a binary tree follows a level order traversal, where ‘#’ signifies a path terminator where no node exists below.

    Here’s an example:
    1

    分析

    一倒判断给定二叉树是否为二叉查找树的题目。

    看似一道很简单的题目,愣是让我提交了4次才AC。

    都卡在了int数据类型溢出问题上了!!! 每每涉及到INT_MIN和INT_MAX的题目都很是头疼。最终还是改变了策略。

    /*
    * 需要注意的是,左子树的所有节点都要比根节点小,
    * 而非只是其左孩子比其小,右子树同样。
    */

    //二叉查找树的一个特点就是其中序遍历结果为一个递增序列,可作为用来判断

    这个简单的判断规则,开始竟没想到,败在了递归判断!

    关于这道题目,这篇博文总结的很好,博文链接

    AC代码

    class Solution {
    public:
        /*
         * 需要注意的是,左子树的所有节点都要比根节点小,
         * 而非只是其左孩子比其小,右子树同样。
         */
        bool isValidBST(TreeNode* root) {
            if (!root)
                return true;
    
            //二叉查找树的一个特点就是其中序遍历结果为一个递增序列,可作为用来判断
            InOrder(root);
    
            int size = ret.size();
            for (int i = 0; i < size - 1; ++i)
            {
                if (ret[i] >= ret[i + 1])
                    return false;
            }//for
            return true;
        }
    
        //中序遍历二叉查找树
        void InOrder(TreeNode *root)
        {
            if (!root)
                return;
    
            InOrder(root->left);
            ret.push_back(root->val);
            InOrder(root->right);
    
        }
    
    private:
        vector<int> ret;
    };

    GitHub测试程序源码

  • 相关阅读:
    【CSS】CSS 页面布局:盒子模型(内容区、边框、内边距、外边距)
    压缩/解压文件
    WebApiClient.JIT
    并行+异步执行操作
    JSON输出时不输出某些属性值
    ASP.NET MVC中Filter过滤器的使用
    使用git克隆github上的项目失败,报错error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054
    C# 实现WebSocket通信
    写日志
    list随机生成数值
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214810.html
Copyright © 2011-2022 走看看