leetcode validate binary search tree
2016-05-30 10:13
375 查看
题目:
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
这道题我想了个解法,就是为每一棵树设置上下界,用递归的算法求解。
然而报错,因为在设置上下限的时候,用Integer.max_value表示正无穷,Integer.min_value表示负无穷,
然而在具体操作的时候,树中有可能就存在Integer.max_value或者Integer.min_value
从而产生错误。
百度了一下,有个很巧妙的解法
即,对BST进行中序遍历,中序遍历的结果必然是升序的。
这道题的解法告诉我们,BST的中序遍历结果是个升序的数组
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
这道题我想了个解法,就是为每一棵树设置上下界,用递归的算法求解。
然而报错,因为在设置上下限的时候,用Integer.max_value表示正无穷,Integer.min_value表示负无穷,
然而在具体操作的时候,树中有可能就存在Integer.max_value或者Integer.min_value
从而产生错误。
百度了一下,有个很巧妙的解法
即,对BST进行中序遍历,中序遍历的结果必然是升序的。
这道题的解法告诉我们,BST的中序遍历结果是个升序的数组
相关文章推荐
- java版简易 nc
- iOS 数据库篇8—FMDB数据库队列
- Device is offline
- Beyond Compare 4 crack
- nRF51822外部中断学习总结
- 无约束极值、线性分类器和线性回归基础
- JavaScript学习--Item16 for 循环和for...in 循环的那点事儿
- Android Listview异步动态加载网络图片
- STM32F0xx_TIM基本延时配置详细过程
- 基因数据处理39之mango安装记录
- 微信支付遇到的超级蛋疼的事
- linux centos 和ubuntu 的安装命令
- 猴子吃桃-倒推法
- 文件的编码
- sdau三 1010
- rm -rf 的“幸存者”
- Python3 爬虫(五) -- 单线程爬取我的CSDN全部博文
- backBarButtonItem 颜色/文字修改
- 文件File操作总结
- 分针与时针之间夹角的计算