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

    提示:

    这道题需要知道一个二叉搜索树的特性,就是一个二叉搜索数的中序遍历结果是一个严格单调递增序列。在知道了这个性质之后,就很好解了,这里我们给出非递归和递归两种解法。

    代码:

    非递归:

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool isValidBST(TreeNode* root) {
            if (!root) {
                return true;
            }
            inOrder(root);
            for (int i = 1; i < v.size(); ++i) {
                if (v[i] <= v[i-1]) {
                    return false;
                }
            }
            return true;
        }
        
        void inOrder(TreeNode* node) {
            if (!node) {
                return;
            }
            inOrder(node->left);
            v.push_back(node->val);
            inOrder(node->right);
        }
        
    private:
        vector<int> v;
    };

    用了一个额外的vector存储中序遍历的结果,看上去好像不是太理想,再看一下递归方法:

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool isValidBST(TreeNode* root) {
            TreeNode* pre = nullptr;
            return isValidBST(root, pre);
        }
        
        bool isValidBST(TreeNode *node, TreeNode*& pre) {
            if (!node) {
                return true;
            }
            if (!isValidBST(node->left, pre)) {
                return false;
            }
            if (pre && node->val <= pre->val) {
                return false;
            }
            pre = node;
            return isValidBST(node->right, pre);
        }
    };

    代码简单了很多,其实遍历的时候还是按照中序的思路来的,但是由于pre指针在函数间传递的过程当中指向的位置会发生改变,因此需要注意在函数参数那里需要将其写为指针的引用。

  • 相关阅读:
    Mac上面Mov转gif
    iOS crash日志分析
    Markdown 学习笔记
    Homebrew安装和使用
    XCode 出现 is missing from working copy文件一直红色情况解决方法
    Mac上面用来录屏的软件(录制gif图片或者mov)
    (十七)Hibnernate 和 Spring 整合
    (十六)Hibernate中的延迟加载
    (十五)Hibernate中的多表操作(5):双向多对多
    (十四)Hibernate中的多表操作(4):单向一对一
  • 原文地址:https://www.cnblogs.com/jdneo/p/5344989.html
Copyright © 2020-2023  润新知