• Leetcode98 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() : 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) {}
     * };
     */
    

    time O(n) space O(1)

    class Solution {
    public:
       int* last = NULL;
       bool isValidBST(TreeNode* root) {
           if (root){
               if(!isValidBST(root->left)) return false;
               if (last && *last>=root->val) return false;
               last = &root->val;
               if(!isValidBST(root->right)) return false;
               return true;
           }else return true;
       };
    };
    
  • 相关阅读:
    Java 泛型约束
    Java 单例模式
    Java中的Atomic包使用指南
    基数排序
    归并排序
    插入排序
    选择排序
    交换排序
    Java多线程 LockSupport
    Java并发控制:ReentrantLock Condition使用详解
  • 原文地址:https://www.cnblogs.com/chanceYu/p/12838033.html
Copyright © 2020-2023  润新知