• 【leetcode】Validate Binary Search Tree(middle)


    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.

    思路:中序遍历。当前值要比之前的小。

    bool isValidBST(TreeNode* root) {
            TreeNode * pPre = NULL;
            TreeNode * pCur = root;
            vector<TreeNode *> v;
    
            while(!v.empty() || NULL != pCur)
            {
                if(NULL != pCur)
                {
                    v.push_back(pCur);
                    pCur = pCur->left;
                }
                else
                {
                    if(pPre != NULL && v.back()->val <= pPre->val)
                        return false;
                    pPre = v.back();    
                    v.pop_back();
                    pCur = pPre->right;
                }
            }
            return true;
        }

    大神递归版:注意,每次左子树的值范围在最小值和根值之间,右子树的范围在根植和最大值之间。

    public class Solution {
        public boolean isValidBST(TreeNode root) {
            return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
        }
    
        public boolean isValidBST(TreeNode root, long minVal, long maxVal) {
            if (root == null) return true;
            if (root.val >= maxVal || root.val <= minVal) return false;
            return isValidBST(root.left, minVal, root.val) && isValidBST(root.right, root.val, maxVal);
        }
    }
  • 相关阅读:
    DOSD用scratch的方式训练通用目标检测,性能很高
    caffemodel模型
    NetScope脱机(localhost)使用[转】
    class前置声明
    const函数
    CUDA开发
    caffe2学习
    faster rcnn讲解很细
    控制台输出覆盖当前行显示
    UA池 代理IP池 scrapy的下载中间件
  • 原文地址:https://www.cnblogs.com/dplearning/p/4481565.html
Copyright © 2020-2023  润新知