java 98.验证二进制搜索树(#1递归).java
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 98.验证二进制搜索树(#1递归).java相关的知识,希望对你有一定的参考价值。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
TreeNode cur = root, pre = null;
while (cur != null) {
if(cur.left == null) {
if (pre != null && cur.val <= pre.val) return false;
pre = cur;
cur = cur.right;
} else {
TreeNode temp = cur.left;
while (temp.right != null && temp.right != cur) {
temp = temp.right;
}
if (temp.right == null) {
temp.right = cur;
cur = cur.left;
} else {
if (pre != null && cur.val <= pre.val) return false;
temp.right = null;
pre = cur;
cur = cur.right;
}
}
}
return true;
}
}
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isValidBST(TreeNode root) {
if (root == null || (root.left == null && root.right == null)){
return true;
}
Stack<TreeNode> s = new Stack<TreeNode>();
TreeNode cur = root;
TreeNode pre = null;
while(true) {
while (cur != null) {
s.add(cur);
cur = cur.left;
}
if (s.isEmpty()) {
break;
}
cur = s.pop();
if(pre != null && pre.val >= cur.val) {
return false;
}
pre = cur;
cur = cur.right;
}
return true;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isValidBST(TreeNode root) {
return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
public boolean isValidBST(TreeNode root, long minVal, long maxVal) {
if (root == null) return true;
if (root.val >= maxVal || root.val <= minVal) return false;
return isValidBST(root.left, minVal, root.val) && isValidBST(root.right, root.val, maxVal);
}
}
以上是关于java 98.验证二进制搜索树(#1递归).java的主要内容,如果未能解决你的问题,请参考以下文章
java 98.验证二进制搜索树(#1递归).java
java 98.验证二进制搜索树(#1递归).java
java 98.验证二进制搜索树(#1递归).java
java 98.验证二进制搜索树(#1递归).java
java刷题-98验证二叉搜索树
LeetCode 树 98. 验证二叉搜索树(二叉搜索树,递归,中序遍历,迭代)