Validate Binary Search Tree
2016-06-03 10:22
253 查看
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.
思路:判断一个BST树是不是有效的。有效的BST树是这样一个树。
如果节点为NULL,则其是一个有效的BST。如果其含有左孩子,左孩子节点的值小于当前节点的val,如果其含有右孩子,右孩子节点的val大于当前节点的val值。其左右孩子也分别是一个BST。代码如下:
/**
* 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 helper(root,INT_MIN,INT_MAX);
}
bool helper(TreeNode *root,int min,int max) //core
{
if(root==NULL)
return true;
return root->val<max&&root->val>min&&helper(root->left,min,root->val)&&helper(root->right,root->val,max);
}
};
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.
思路:判断一个BST树是不是有效的。有效的BST树是这样一个树。
如果节点为NULL,则其是一个有效的BST。如果其含有左孩子,左孩子节点的值小于当前节点的val,如果其含有右孩子,右孩子节点的val大于当前节点的val值。其左右孩子也分别是一个BST。代码如下:
/**
* 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 helper(root,INT_MIN,INT_MAX);
}
bool helper(TreeNode *root,int min,int max) //core
{
if(root==NULL)
return true;
return root->val<max&&root->val>min&&helper(root->left,min,root->val)&&helper(root->right,root->val,max);
}
};
相关文章推荐
- CREATING AN ANGULAR 2 BUILD WITH GULP, TSLINT AND DEFINITELYTYPED
- Flatten Binary Tree to Linked List
- 线性回归
- numpy读写文件
- JDBC之批量操作与注意事项浅析
- 使用CXF开发RESTFul服务
- 窗口化Activity实现效果
- Maven-window版 简单使用(apache-maven-3.3.9)
- MyEclipse8.5集成Tomcat7时的启动错误:Exception in thread “main” java.lang.NoClassDefFoundError org/apache/com
- ext4.2.1路径
- 双线服务器托管因时代的发展产生的优势
- 【数据结构】常见的排序方法的实现以及性能对比
- WPF编译时提示"xxx不包含适合于入口点的静态 Main方法xxx"
- 团队冲刺2---个人工作总结十(6.3)
- SVN使用Tips
- Leetcode 145. Binary Tree Postorder Traversal
- 利用Linux Live CD更改esxi主机root密码
- 自定义类封装数组,并对数组进行CRUD操作;有序数组的实习与查找
- memcached在windows环境下的安装
- Android : AlarmManager