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

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

标题 Validate Binary Search Tree
通过率 21.9%
难度 中等

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.

 

confused what "{1,#,2,3}" means? 

本题就是确定一棵树是否为二叉排序树,左<中<右,可以用中序遍历去判断,也可以用一个范围值去判断当前节点是否在其中,范围的下界是左边的树,范围的右界是右边的树,直接看代码了:

1 /** 2  * Definition for binary tree 3  * public class TreeNode { 4  *     int val; 5  *     TreeNode left; 6  *     TreeNode right; 7  *     TreeNode(int x) { val = x; } 8  * } 9  */10 public class Solution {11     public boolean isValidBST(TreeNode root) {12         return isBst(root,Long.MIN_VALUE,Long.MAX_VALUE);13     }14     public boolean isBst(TreeNode root,long min,long max){15     if(root==null) return true;16     if(root.val<=min||root.val>=max)return false;17     return isBst(root.left,min,root.val)&&isBst(root.right,root.val,max);18        19     }20 }

 

转载于:https://www.cnblogs.com/pkuYang/p/4299366.html

你可能感兴趣的文章
关于php网页内容更改但刷新不起作用的问题
查看>>
SDWebImage在xcode6.1的iOS8环境下报错
查看>>
Iptables—包过滤(网络层)防火墙
查看>>
大龄程序员,关于编程与管理的思考
查看>>
前端进阶 -js数据结构类型扩展:immutable-js(10)
查看>>
centos5.10NFS服务的配置
查看>>
有关二分查找的边界思考
查看>>
phpvirtualbox访问Ubuntu虚拟机134-配置详情
查看>>
Java 单元测试利器之 Junit
查看>>
我的友情链接
查看>>
媒体关注OSV智能桌面虚拟化平台
查看>>
安装VMware Workstation提示the msi failed的解决办法
查看>>
MongoDB安装配置
查看>>
使程序在Linux下后台运行
查看>>
webpack构建h5plus多页面移动app
查看>>
Varnish缓存更新策略调试过程
查看>>
unix bsd linux gun 粗略解释
查看>>
shell中特殊符号的用法
查看>>
我的友情链接
查看>>
上传贴图
查看>>