• 【题解】【BST】【Leetcode】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.

    思路:

    这题其实考查的是BST的定义,下面code的是CC150v5上的第一种答案简化版,同样借鉴中序遍历的思想,但是只保存当前点上家的值,判断当前点是否大于上家。

    代码:

     1 bool isValidBST(TreeNode *root) {
     2     int init = INT_MIN;
     3     return isValidNode(root, init);
     4 }
     5 bool isValidNode(TreeNode *root, int& lastVal){
     6     if(root == NULL)
     7         return true;
     8 
     9     if(!isValidNode(root->left, lastVal))
    10         return false;
    11         
    12     if(root->val <= lastVal) //不是<而是<=,failed {1,1}=>false
    13         return false;
    14     lastVal = root->val;
    15     
    16     if(!isValidNode(root->right, lastVal))
    17         return false;
    18     
    19     return true;//忘写最后一句了
    20 }
  • 相关阅读:
    高并发下秒杀商品,必须知道的9个细节
    linux下关闭网络命令
    Linux系统模拟网络测试
    20211215
    观影大数据分析(上)
    2021冬季学期有感
    观影大数据分析(中)
    Docker安装Oracle
    2022寒假安排
    Docker安装Mongo
  • 原文地址:https://www.cnblogs.com/wei-li/p/ValidateBinarySearchTree.html
Copyright © 2020-2023  润新知