zoukankan      html  css  js  c++  java
  • 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;
       };
    };
    
  • 相关阅读:
    2019.8.16
    一种抠环的办法
    [HAOI2015]树上染色
    有关树形背包
    2019.7.27
    有关矩阵快速幂
    2019.7.25
    欧拉函数(转载)
    2019.7.22
    phpstudy集成环境安装redis扩展
  • 原文地址:https://www.cnblogs.com/chanceYu/p/12838033.html
Copyright © 2011-2022 走看看