题目描述

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);
}
};

答案分析

最新文章

  1. C#移动跨平台开发(1)环境准备
  2. JS阻止事件冒泡
  3. Mysql导入数据命令
  4. Ext.Net MVC 配置(1)
  5. emacs最简单入门,只要10分钟
  6. 用CSS定义每段首行缩进2个字符 转
  7. 反射中getMethods 与 getDeclaredMethods 的区别
  8. eclipse workspace 共享配置文件
  9. spring+websocket整合
  10. &quot;HTTP 错误 500.19 请求的页面的相关配置数据无效&quot; 解决办法
  11. 使用python三方库xlrd解析excel数据
  12. Projected Coordinate Systems
  13. SQLite设置主键自动增长及插入语法
  14. python学习笔记(一)元组,序列,字典
  15. MYSQLI DEMO
  16. Angularjs $http服务的两个request安全问题
  17. HTML5和CSS3的新特性
  18. MinGW GCC 8.3.1 2019年2月23日 出炉啦
  19. Linux磁盘空间被占用问题 (分区目录占用空间比实际空间要大: 资源文件删除后, 空间没有真正释放)
  20. linux 关闭笔记本自带键盘

热门文章

  1. 零基础Python入门(1)- python安装与预热
  2. java实例化对象的过程
  3. 我的BO之状态控制
  4. php基础总结
  5. T-MAX—项目系统设计与数据库设计
  6. Nginx中文文档-安装 Nginx
  7. tornado异步请求响应速度的实例测试
  8. Angular 中的数据交互(get jsonp post)
  9. osgViewer::View::setUpViewOnSingleScreen()
  10. win10下安装Kafka