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:

Input:
2
/ \
1 3
Output: true

Example 2:

    5
/ \
1 4
  / \
  3 6
Output: false
Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value
  is 5 but its right child's value is 4.

这道验证二叉搜索树有很多种解法,可以利用它本身的性质来做,即左<根<右,也可以通过利用中序遍历结果为有序数列来做,下面我们先来看最简单的一种,就是利用其本身性质来做,初始化时带入系统最大值和最小值,在递归过程中换成它们自己的节点值,用long代替int就是为了包括int的边界条件,代码如下:

C++ 解法一:

// Recursion without inorder traversal
class Solution {
public:
bool isValidBST(TreeNode* root) {
return isValidBST(root, LONG_MIN, LONG_MAX);
}
bool isValidBST(TreeNode* root, long mn, long mx) {
if (!root) return true;
if (root->val <= mn || root->val >= mx) return false;
return isValidBST(root->left, mn, root->val) && isValidBST(root->right, root->val, mx);
}
};

Java 解法一:

public class Solution {
public boolean isValidBST(TreeNode root) {
if (root == null) return true;
return valid(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
public boolean valid(TreeNode root, long low, long high) {
if (root == null) return true;
if (root.val <= low || root.val >= high) return false;
return valid(root.left, low, root.val) && valid(root.right, root.val, high);
}
}

这题实际上简化了难度,因为有的时候题目中的二叉搜索树会定义为左<=根<右,而这道题设定为一般情况左<根<右,那么就可以用中序遍历来做。因为如果不去掉左=根这个条件的话,那么下边两个数用中序遍历无法区分:

20       20
   /           \
 20           20

它们的中序遍历结果都一样,但是左边的是 BST,右边的不是 BST。去掉等号的条件则相当于去掉了这种限制条件。下面来看使用中序遍历来做,这种方法思路很直接,通过中序遍历将所有的节点值存到一个数组里,然后再来判断这个数组是不是有序的,代码如下:

C++ 解法二:

// Recursion
class Solution {
public:
bool isValidBST(TreeNode* root) {
if (!root) return true;
vector<int> vals;
inorder(root, vals);
for (int i = ; i < vals.size() - ; ++i) {
if (vals[i] >= vals[i + ]) return false;
}
return true;
}
void inorder(TreeNode* root, vector<int>& vals) {
if (!root) return;
inorder(root->left, vals);
vals.push_back(root->val);
inorder(root->right, vals);
}
};

Java 解法二:

public class Solution {
public boolean isValidBST(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
inorder(root, list);
for (int i = 0; i < list.size() - 1; ++i) {
if (list.get(i) >= list.get(i + 1)) return false;
}
return true;
}
public void inorder(TreeNode node, List<Integer> list) {
if (node == null) return;
inorder(node.left, list);
list.add(node.val);
inorder(node.right, list);
}
}

下面这种解法跟上面那个很类似,都是用递归的中序遍历,但不同之处是不将遍历结果存入一个数组遍历完成再比较,而是每当遍历到一个新节点时和其上一个节点比较,如果不大于上一个节点那么则返回 false,全部遍历完成后返回 true。代码如下:

C++ 解法三:

class Solution {
public:
bool isValidBST(TreeNode* root) {
TreeNode *pre = NULL;
return inorder(root, pre);
}
bool inorder(TreeNode* node, TreeNode*& pre) {
if (!node) return true;
bool res = inorder(node->left, pre);
if (!res) return false;
if (pre) {
if (node->val <= pre->val) return false;
}
pre = node;
return inorder(node->right, pre);
}
};

当然这道题也可以用非递归来做,需要用到栈,因为中序遍历可以非递归来实现,所以只要在其上面稍加改动便可,代码如下:

C++ 解法四:

class Solution {
public:
bool isValidBST(TreeNode* root) {
stack<TreeNode*> s;
TreeNode *p = root, *pre = NULL;
while (p || !s.empty()) {
while (p) {
s.push(p);
p = p->left;
}
p = s.top(); s.pop();
if (pre && p->val <= pre->val) return false;
pre = p;
p = p->right;
}
return true;
}
};

Java 解法四:

public class Solution {
public boolean isValidBST(TreeNode root) {
Stack<TreeNode> s = new Stack<TreeNode>();
TreeNode p = root, pre = null;
while (p != null || !s.empty()) {
while (p != null) {
s.push(p);
p = p.left;
}
p = s.pop();
if (pre != null && p.val <= pre.val) return false;
pre = p;
p = p.right;
}
return true;
}
}

最后还有一种方法,由于中序遍历还有非递归且无栈的实现方法,称之为 Morris 遍历,可以参考博主之前的博客 Binary Tree Inorder Traversal,这种实现方法虽然写起来比递归版本要复杂的多,但是好处在于是 O(1) 空间复杂度,参见代码如下:

C++ 解法五:

class Solution {
public:
bool isValidBST(TreeNode *root) {
if (!root) return true;
TreeNode *cur = root, *pre, *parent = NULL;
bool res = true;
while (cur) {
if (!cur->left) {
if (parent && parent->val >= cur->val) res = false;
parent = cur;
cur = cur->right;
} else {
pre = cur->left;
while (pre->right && pre->right != cur) pre = pre->right;
if (!pre->right) {
pre->right = cur;
cur = cur->left;
} else {
pre->right = NULL;
if (parent->val >= cur->val) res = false;
parent = cur;
cur = cur->right;
}
}
}
return res;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/98

类似题目:

Binary Tree Inorder Traversal

Find Mode in Binary Search Tree

参考资料:

https://leetcode.com/problems/validate-binary-search-tree/

https://leetcode.com/problems/validate-binary-search-tree/discuss/32101/My-java-inorder-iteration-solution

https://leetcode.com/problems/validate-binary-search-tree/discuss/32109/My-simple-Java-solution-in-3-lines

https://leetcode.com/problems/validate-binary-search-tree/discuss/32112/Learn-one-iterative-inorder-traversal-apply-it-to-multiple-tree-questions-(Java-Solution)

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Validate Binary Search Tree 验证二叉搜索树的更多相关文章

  1. [CareerCup] 4.5 Validate Binary Search Tree 验证二叉搜索树

    4.5 Implement a function to check if a binary tree is a binary search tree. LeetCode上的原题,请参见我之前的博客Va ...

  2. [LeetCode] 98. Validate Binary Search Tree 验证二叉搜索树

    Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as ...

  3. [leetcode]98. Validate Binary Search Tree验证二叉搜索树

    Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as ...

  4. 098 Validate Binary Search Tree 验证二叉搜索树

    给定一个二叉树,判断其是否是一个有效的二叉搜索树.一个二叉搜索树有如下定义:    左子树只包含小于当前节点的数.    右子树只包含大于当前节点的数.    所有子树自身必须也是二叉搜索树.示例 1 ...

  5. Leetcode98. Validate Binary Search Tree验证二叉搜索树

    给定一个二叉树,判断其是否是一个有效的二叉搜索树. 假设一个二叉搜索树具有如下特征: 节点的左子树只包含小于当前节点的数. 节点的右子树只包含大于当前节点的数. 所有左子树和右子树自身必须也是二叉搜索 ...

  6. [LeetCode] Verify Preorder Sequence in Binary Search Tree 验证二叉搜索树的先序序列

    Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary ...

  7. [LeetCode] 255. Verify Preorder Sequence in Binary Search Tree 验证二叉搜索树的先序序列

    Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary ...

  8. [LeetCode] Recover Binary Search Tree 复原二叉搜索树

    Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...

  9. [Leetcode] Recover binary search tree 恢复二叉搜索树

    Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...

随机推荐

  1. Java正则速成秘籍(三)之见招拆招篇

    导读 正则表达式是什么?有什么用? 正则表达式(Regular Expression)是一种文本规则,可以用来校验.查找.替换与规则匹配的文本. 又爱又恨的正则 正则表达式是一个强大的文本匹配工具,但 ...

  2. spring/spring boot/spring cloud开发总结

    背景        针对RPC远程调用,都在使用dubbo.dubbox等,我们也是如此.由于社区暂停维护.应对未来发展,我们准备尝试新技术(或许这时候也不算什么新技术了吧),选择使用了spring ...

  3. 解决ngnix服务器上的Discuz!x2.5 Upload Error:413错误

    1.修改php.ini sudo nano /etc/php5/fpm/php.ini #打开php.ini找到并修改以下的参数,目的是修改上传限制 max_execution_time = 900 ...

  4. H5 WebSocket 如何和C#进行通信

    HTML5作为下一代的 Web 标准, 拥有许多引人注目的新特性,如 Canvas.本地存储.多媒体编程接口.WebSocket 等.WebSocket 在浏览器和服务器之间提供了一个基于 TCP 连 ...

  5. js模仿ios select效果

    github:https://github.com/zhoushengmufc/iosselect webapp模仿ios下拉菜单 html下拉菜单select在安卓和IOS下表现不一样,iossel ...

  6. htm常用标签总结

    1.结构性定义 文件类型 <HTML></HTML> (放在档案的开头与结尾) 文件主题 <TITLE></TITLE> (必须放在「文头」区块内) 文 ...

  7. Javascript绝不要使用在文档加载之后使用 document.write(), 怎么理解?

    在文档加载之后使用 document.write(),会覆盖该文档.   需满足两个条件:      1.在函数内部调用document.write():      2.通过按钮响应调用函数:   举 ...

  8. 初窥Javascript单元测试,附带掌握一门新技能的学习方式。

    之前没感觉要学啥单元测试,项目中测试都是手动测的,但也没觉的啥,但最近看文章和招聘上也多多少少有这方面的需求,于是网上搜索了一下,只找到了一些文章,但介绍的都不是很详细或者说比较复杂,满满的伤,虽然看 ...

  9. DevExpress VCL v16.1.3发布

    ExpressPDFViewer # BC3840:包含action标题和action提示的 Action classes 和 resource strings 重命名: class名称末尾中包含'A ...

  10. listview侧滑删除

    自定义Listview,向左滑动,右边刚好显示删除按钮: public class SlideListView extends ListView { private int mScreenWidth; ...