LeetCode之“树”:Validate Binary Search Tree
2015-07-08 19:59
381 查看
题目链接
题目要求:
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
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:
The above binary tree is serialized as
用惯性思维(即判断某节点的值与其左右子节点的值得关系)去解决这道题,相对麻烦些(花了比较多的时间,最后还是很难兼顾各种情况)。我们可以用中序遍历的方法将整棵树输出,然后再判断输出序列是否是递增序列就行了。
还有一篇博文的想法特别好,我们要将关注点放在节点本身,然后不断更新它的上下限。
具体程序如下:
上边程序用到了LONG_MIN、LONG_MAX,主要是为了应付比较极端的测试集。下图是C/C++中个数据类型的最大值宏定义列表:
题目要求:
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:
1 / \ 2 3 / 4 \ 5
The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}".
用惯性思维(即判断某节点的值与其左右子节点的值得关系)去解决这道题,相对麻烦些(花了比较多的时间,最后还是很难兼顾各种情况)。我们可以用中序遍历的方法将整棵树输出,然后再判断输出序列是否是递增序列就行了。
还有一篇博文的想法特别好,我们要将关注点放在节点本身,然后不断更新它的上下限。
具体程序如下:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isValidBST(TreeNode* root) { return isValidBSTSub(root, LONG_MIN, LONG_MAX); } bool isValidBSTSub(TreeNode *tree, long alpha, long beta) { if(!tree) return true; if(tree->val > alpha && tree->val < beta) return isValidBSTSub(tree->left, alpha, tree->val) && isValidBSTSub(tree->right, tree->val, beta); else return false; } };
上边程序用到了LONG_MIN、LONG_MAX,主要是为了应付比较极端的测试集。下图是C/C++中个数据类型的最大值宏定义列表:
![](http://img.ddvip.com/2014_0917/36811410914339.png)
相关文章推荐
- MyBatis知多少(1)
- 南阳oj 题目40 公约数和公倍数
- 开张致喜
- zstack -Serial Boot Loader(串口下程序)
- 凸优化:ADMM(Alternating Direction Method of Multipliers)交替方向乘子算法系列之六: L1-Norm Problems
- 网络请求回来json数据时去空格以及标示符
- android系统语言设置对app本身的影响
- 易經大意原稿(頁單位) 051-075
- Objective-C字符串处理
- vmware安装CentOS6.4详细步骤
- Python Web初学解惑之 WSGI、flup、fastcgi、web.py的关系
- 莫队算法
- HTTP协议中PUT和POST使用上的区别
- 随笔2
- Xcode设置项之Architectures和Valid Architectures
- CGI相关介绍
- I2C总线-I2C总线介绍
- HTML+CSS实现导航页
- mapreduce在hive中执行成功,在beeline中执行失败的问题解决
- 如何利用phpize在生产环境中为php添加新的扩展php-bcmath