博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【Leetcode刷题篇】leetcode98 判断一棵树是否为二叉搜索树
阅读量:1887 次
发布时间:2019-04-26

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

题目:给定一个二叉树,判断其是否是一个有效的二叉搜索树。

假设一个二叉搜索树具有如下特征:

  • 节点的左子树只包含小于当前节点的数。
  • 节点的右子树只包含大于当前节点的数。
  • 所有左子树和右子树自身必须也是二叉搜索树。
/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */class Solution {
public boolean isValidBST(TreeNode root) {
// 中序遍历来解决该题目 if(root==null){
return true; } // 栈 Stack
stack = new Stack<>(); long pre = Long.MIN_VALUE; while(root!=null || !stack.isEmpty()){
if(root!=null){
stack.push(root); root = root.left; }else{
root = stack.pop(); // 处理数据 if(pre!=Long.MIN_VALUE && root.val<=pre){
return false; } pre = root.val; root = root.right; } } return true; }}

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

你可能感兴趣的文章
torch.nn.Embedding的使用
查看>>
排序算法(五)快速排序的实现(python)
查看>>
使用邻接表实现数据结构图(python)
查看>>
图的非递归深搜遍历图示与代码(python)
查看>>
拓扑排序的实现(python)
查看>>
matplotlib绘图接口和绘制线性图
查看>>
bugku 做题 misc 方向
查看>>
Maltego 学习与使用
查看>>
Python开源项目合集(网页框架)
查看>>
C语言标准库所包含的函数功能介绍
查看>>
C++ builder热键处理方式(HotKey)
查看>>
BCB和Delphi 执行顺序与快捷键
查看>>
Opencv+Python+USB摄像头 人脸识别
查看>>
OPENCV+PYTHON 文字识别(重点图像透视变换)
查看>>
利用Opencv+Python 实现二维码识别
查看>>
python函数的参数形式
查看>>
python 共享文件夹 cmd命令
查看>>
Vue3.0发布了初始版本, 抢先体验新特性,API全部函数化
查看>>
掌握这8个CSS开发工具让你瞬间成为开发高手
查看>>
Django简介、ORM、核心模块
查看>>