上篇文章 判断是否是平衡二叉树 ,这篇文章来看下是否是二叉搜索树。
假设一个二叉搜索树具有如下特征:
- 节点的左子树只包含小于当前节点的数。
- 节点的右子树只包含大于当前节点的数。
- 所有左子树和右子树自身必须也是二叉搜索树。 注意,上面的定义,是 节点的 左子树 只包含小于当前节点的数。是左子树,而不是仅仅要求 左孩子 小于 当前节点。左子树的意思是:当前节点所有左边的节点都小于当前节点。
所以,下面的代码是错误的:
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
int val = root.val;
if (root.left != null && root.left.val >= val) {
return false;
}
if (root.right != null && root.right.val <= val) {
return false;
}
if (!isValidBST(root.left) || !isValidBst(root.right)) {
return false;
}
return true;
}
上图的树满足程序代码,但是左子树的节点7却大于根节点6,不是二叉搜索树。
正确的解法:
public boolean isValidBST(TreeNode root) {
return helper(root, null, null);
}
private boolean helper(TreeNode root, Integer lower, Integer upper) {
if (root == null) {
return true;
}
int val = root.val;
if (lower != null && lower >= val) {
return false;
}
if (upper != null && val >= upper) {
return false;
}
if (!helper(root.left, lower, val) || !helper(root.right, val, upper)) {
return false;
}
return true;
}
update 20210317
class Solution {
public boolean isValidBST(TreeNode root) {
return foo(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private boolean foo(TreeNode root, Long low, Long high) {
if (root == null) {
return true;
}
int val = root.val;
if (val <= low) {
return false;
}
if (val >= high) {
return false;
}
if (!foo(root.left, low, (long) val) || !foo(root.right, (long) val, high)) {
return false;
}
return true;
}
}
二叉搜索树有一个特点:二叉搜索树的中序遍历是个单调递增的序列。也就是前面访问的节点肯定比后面的小。因此,可以中序遍历判断下。
public boolean isValidBST(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
double inOrder = -Double.MAX_VALUE;
while (!stack.empty() || root != null) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
if (root.val <= inOrder) {
return false;
}
inOrder = root.val;
root = root.right;
}
return true;
}
update 20210315
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode p = root;
long last = Long.MIN_VALUE;
while (p != null || !stack.isEmpty()) {
if (p != null) {
stack.push(p);
p = p.left;
} else {
p = stack.pop();
if (p.val <= last) {
return false;
}
last = p.val;
p = p.right;
}
}
return true;
}
}
硬广告
欢迎关注公众号:double6
final
本文正在参与「掘金 2021 春招闯关活动」, 点击查看 活动详情