LeetCode Validate Binary Search Tree
来源:互联网 发布:cf2.0优化 编辑:程序博客网 时间:2024/05/21 10:04
题目
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.
探测一个二叉树的合法性。
每个左子树上的点的值不能大于等于当前元素的值,每个右子树上的点的值不能小于等于当前值。
记录值的限制,递归调用即可。
代码:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:bool innerBST(TreeNode *root,long long min,long long max)//迭代扫描,根,可以取的最小合法值,可以取的最大合法值{if(root==NULL)//NULL为合法return true;if(root->left!=NULL&&(root->left->val>=root->val||root->left->val<=min))//左子树的值是否合法return false;if(root->right!=NULL&&(root->right->val<=root->val||root->right->val>=max))//右子树的值是否合法return false;if(innerBST(root->left,min,root->val)&&innerBST(root->right,root->val,max))//判断左右子树是否合法return true;return false;//否则不合法} bool isValidBST(TreeNode *root) { return innerBST(root,(long long)LONG_MIN-1,(long long)LONG_MAX+1); }};
0 0
- LeetCode: Validate Binary Search Tree
- [Leetcode] Validate Binary Search Tree
- LeetCode : Validate Binary Search Tree
- [LeetCode] Validate Binary Search Tree
- [LeetCode] Validate binary search tree
- [LeetCode]Validate Binary Search Tree
- [Leetcode]Validate Binary Search Tree
- [leetcode]Validate Binary Search Tree
- LeetCode-Validate Binary Search Tree
- [leetcode] Validate Binary Search Tree
- LeetCode - Validate Binary Search Tree
- [LeetCode] Validate Binary Search Tree
- Leetcode Validate Binary Search Tree
- LeetCode | Validate Binary Search Tree
- LeetCode - Validate Binary Search Tree
- Leetcode: Validate Binary Search Tree
- 【Leetcode】Validate Binary Search Tree
- 【leetcode】Validate Binary Search Tree
- tomcat在ubuntu中设置开机启动
- myeclipse10配置maven
- 适配器模式的理解
- 忽略大小写的字符串比较
- 获取已安装apk文件信息
- LeetCode Validate Binary Search Tree
- Apache Maven 使用 profile 和 filtering 实现多种环境下的资源配置管理(属性过滤)
- 转载 android 自定义view
- 用图片撑开的div,里面的input标签在三星手机不生效解决办法
- Hibernate 主键生成策略
- B树算法与实现
- 编写maven插件的时候,简化插件的输入命令方法
- ubuntu系统安装
- safe_mode 开启后linux下影响