• LeetCode Validate Binary Search Tree


    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool isValidBST(TreeNode *root) {
            return dfs(root, 0, 0, 0);
        }
        
        bool dfs(TreeNode *root, int lower, int upper, int part) {
            if (root == NULL) return true;
            if ((part & 0x1) && lower >= root->val) return false;
            if ((part & 0x2) && upper <= root->val) return false;
            return dfs(root->left, lower, root->val, part | 0x2) 
                    && dfs(root->right, root->val, upper, part | 0x1);
        }
    };

    dfs,初最左边和最右边的分支(前者只有上界,后者只有下界),其他节点都有一个上界和下界,将节点值和这个范围比较即可。

    第二轮:

    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.

    还可以使用中序遍历检测遍历得到的序列是否是递增的

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    private:
        bool val_set;
        int pre_val;
    public:
        bool isValidBST(TreeNode *root) {
            val_set = false;
            return inorder(root);
        }
        
        bool inorder(TreeNode* root) {
            if (root == NULL) {
                return true;
            }
            if (!inorder(root->left)) {
                return false;
            }
            if (!val_set) {
                pre_val = root->val;
                val_set = true;
            } else {
                if (pre_val >= root->val) {
                    return false;
                }
                pre_val = root->val;
            }
            return inorder(root->right);
        }
    };
  • 相关阅读:
    PHP数组简介
    如何在不使用系统函数的情况下实现PHP中数组系统函数的功能
    弹性盒布局display:flex详解
    关于JS面向对象中原型和原型链以及他们之间的关系及this的详解
    如何使用AngularJS对表单提交内容进行验证
    如何用canvas画布画旋转的五角星
    MYSQL常用函数以及如何操作数据
    数据库基础以及表的创建
    PHP中的OOP
    PHP中数组的遍历
  • 原文地址:https://www.cnblogs.com/lailailai/p/3805038.html
Copyright © 2020-2023  润新知