博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
98. Validate Binary Search Tree
阅读量:6908 次
发布时间:2019-06-27

本文共 1523 字,大约阅读时间需要 5 分钟。

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.
Example 1:

Input:    2   / \  1   3Output: true

Example 2:

5   / \  1   4     / \    3   6Output: falseExplanation: The input is: [5,1,4,null,null,3,6]. The root node's value is 5 but its right child's value is 4.

难度:medium

题目:给定二叉树,判断其是否为二叉搜索树。

思路:递归,并记录当前结点的取值范围。

Runtime: 0 ms, faster than 100.00% of Java online submissions for Validate Binary Search Tree.

Memory Usage: 37.6 MB, less than 100.00% of Java online submissions for Validate Binary Search Tree.

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public boolean isValidBST(TreeNode root) {        if (null == root) {            return true;        }                return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);    }    public boolean isValidBST(TreeNode root, long minVal, long maxVal) {        if (null == root) {            return true;        }                if (root.val >= maxVal || root.val <= minVal) {            return false;        }                return isValidBST(root.left, minVal, root.val) && isValidBST(root.right, root.val, maxVal);    }}

转载地址:http://drgdl.baihongyu.com/

你可能感兴趣的文章
NetFlow是一种数据交换方式,提供网络流量的会话级视图,记录下每个TCP/IP事务的信息...
查看>>
手机网页Html代码实现(解决显示页面很小的问题)
查看>>
指针与储物箱的关系
查看>>
sqlserver 的事务和c#的事务
查看>>
kernelchina.org内核研究
查看>>
模拟Asp.Net Forums实现可以换皮肤的控件 (转载)
查看>>
python使用(一)
查看>>
认真分析mmap:是什么 为什么 怎么用【转】
查看>>
ios 上拉载入下拉刷新Dome
查看>>
Objective-C:NSMutableString类的常见操作
查看>>
用javascript操作xml
查看>>
突破Windows系统默认用户句柄与GDI句柄限制
查看>>
SQLServer 2016安装时的错误:Polybase要求安装Oracle JRE 7更新51或更高版本
查看>>
光流定位原理是什么??【转】
查看>>
POJ 2778 DNA Sequence (AC自己主动机 + dp)
查看>>
JS排序的运用
查看>>
堆排序
查看>>
uC/OS-II源码分析(一)
查看>>
Redis自学笔记 --string类型
查看>>
【c++】动态绑定
查看>>