zoukankan      html  css  js  c++  java
  • 【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);
        }
    }
  • 相关阅读:
    MySQL5.7(64位)windows下的安装
    Python---更改pip源
    .NET WEB技术小记
    前端板书1
    Hadoop伪分布式系统的搭建(ubuntu)
    Hive的基本操作
    SQLServer2008附加数据库不成功 操作系统错误5
    VUE学习小结
    jQuery入门基础(选择器)
    Linq(高级查询)
  • 原文地址:https://www.cnblogs.com/dplearning/p/4481565.html
Copyright © 2011-2022 走看看