LeetCode(98) Validate Binary Search Tree
2015-10-12 16:00
399 查看
题目
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? > read more on how binary tree is serialized on OJ.
OJ’s Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where ‘#’ signifies a path terminator where no node exists below.
Here’s an example:
分析
一倒判断给定二叉树是否为二叉查找树的题目。看似一道很简单的题目,愣是让我提交了4次才AC。
都卡在了int数据类型溢出问题上了!!! 每每涉及到INT_MIN和INT_MAX的题目都很是头疼。最终还是改变了策略。
/*
* 需要注意的是,左子树的所有节点都要比根节点小,
* 而非只是其左孩子比其小,右子树同样。
*/
//二叉查找树的一个特点就是其中序遍历结果为一个递增序列,可作为用来判断
这个简单的判断规则,开始竟没想到,败在了递归判断!
关于这道题目,这篇博文总结的很好,博文链接。
AC代码
class Solution { public: /* * 需要注意的是,左子树的所有节点都要比根节点小, * 而非只是其左孩子比其小,右子树同样。 */ bool isValidBST(TreeNode* root) { if (!root) return true; //二叉查找树的一个特点就是其中序遍历结果为一个递增序列,可作为用来判断 InOrder(root); int size = ret.size(); for (int i = 0; i < size - 1; ++i) { if (ret[i] >= ret[i + 1]) return false; }//for return true; } //中序遍历二叉查找树 void InOrder(TreeNode *root) { if (!root) return; InOrder(root->left); ret.push_back(root->val); InOrder(root->right); } private: vector<int> ret; };
GitHub测试程序源码
相关文章推荐
- 生成唯一id
- NSIS 的 Modern UI 教程(二)
- 千分位格式化 数字格式化 fmt:formatNumber 和DecimalFormat java千分位格式化
- 字符串拼接函数
- camera调试
- linux常见命令
- 002-Impala架构
- 解读ASP.NET 5 & MVC6系列(7):依赖注入
- 有用的DOS命令
- Struts2中Action接收参数的四种形式
- CSS 实例
- 稀有的二维狄拉克材料
- html5视频播放解决方案
- 5G移动网络 V2X
- UI:使View背景逐渐变暗的方法
- table_schem是什么意思
- [leetcode 289]Game of Life
- jQuery $(document).ready()和JavaScript onload事件详解区别
- 工薪青年投资理财必须明白的基本道理
- 蓝牙开启流程(enable)分析