LeetCode 098 Validate Binary Search Tree
2015-10-27 23:15
417 查看
题目描述
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.
分析
验证一棵树是否为BST,只需要验证中序遍历序列是否是递增的。代码
[code] boolean failed = false; // 要用long,而不是int // 否则涉及到Integer.MIN_VALUE的用例会出现错误 // 比如{Integer.MIN_VALUE}这个用例会错误 long last = Long.MIN_VALUE; public boolean isValidBST(TreeNode root) { if (root == null) { return true; } inorder(root); return !failed; } private void inorder(TreeNode root) { if (root == null || failed) { return; } // 左 inorder(root.left); // 中,相当于中序遍历中的打印操作 // 只采用了一个变量,所以空间复杂度是O(1) // 传统的做法是建立一个ArrayList,然后判断中序遍历是否是递增的,但是空间复杂度是O(n) if (last >= root.val) { failed = true; } last = root.val; // 右 inorder(root.right); }
相关文章推荐
- web前端之JavaScrip的对象
- 定义注解接口
- Android问题之PopupWindow GridView onItemClick无效
- Linux集群规划
- C语言程序入门第一节课/4
- Activity布局初步
- cnBlogs windows LIves Writes 安装
- PHP快速抓取快递信息
- android--(联系人提供者实践)
- POJ 2828(线段树 单点更新)
- fs4412开发板学习笔记(三)
- LightOJ - 1025 The Specials Menu(区间DP)
- Eclipse环境快速搭载
- vSphere 6.0中VM Component Protection(VMCP)详细解析
- LeetCode 103: Binary Tree Zigzag Level Order Traversal
- [Linux]cmake工具的使用
- 添加右键菜单
- UITableView和UITableViewCell的几种样式
- ant 环境配置
- SQL Server数据库相关知识(一)