LC 98. Validate Binary Search Tree
2024-09-01 14:55:12
题目描述
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.
Example 1:
2
/ \
1 3 Input: [2,1,3]
Output: true
Example 2:
5
/ \
1 4
/ \
3 6 Input: [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.
参考答案
class Solution {
public:
bool isValidBST(TreeNode* root) {
return foo(root,NULL,NULL);
}
bool foo(TreeNode* root,TreeNode* minNode,TreeNode* maxNode){
if(!root) return true;
if(minNode && root->val <= minNode->val || maxNode && root->val >= maxNode->val) return false;
return foo(root->left,minNode,root) && foo(root->right,root,maxNode);
}
};
答案分析
最新文章
- C#移动跨平台开发(1)环境准备
- JS阻止事件冒泡
- Mysql导入数据命令
- Ext.Net MVC 配置(1)
- emacs最简单入门,只要10分钟
- 用CSS定义每段首行缩进2个字符 转
- 反射中getMethods 与 getDeclaredMethods 的区别
- eclipse workspace 共享配置文件
- spring+websocket整合
- ";HTTP 错误 500.19 请求的页面的相关配置数据无效"; 解决办法
- 使用python三方库xlrd解析excel数据
- Projected Coordinate Systems
- SQLite设置主键自动增长及插入语法
- python学习笔记(一)元组,序列,字典
- MYSQLI DEMO
- Angularjs $http服务的两个request安全问题
- HTML5和CSS3的新特性
- MinGW GCC 8.3.1 2019年2月23日 出炉啦
- Linux磁盘空间被占用问题 (分区目录占用空间比实际空间要大: 资源文件删除后, 空间没有真正释放)
- linux 关闭笔记本自带键盘