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

public class IsValidBST {
@Test
public void isValidBSTTest1() {
TreeNode input = new TreeNode(2);
input.left = new TreeNode(1);
input.right = new TreeNode(3);
Assert.assertTrue(isValidBST(input));
}
@Test
public void isValidBSTTest2() {
TreeNode input = new TreeNode(2);
input.left = new TreeNode(1);
input.right = new TreeNode(3);
input.left.left = new TreeNode(4);
Assert.assertFalse(isValidBST(input));
}
@Test
public void isValidBSTTest3() {
TreeNode input = new TreeNode(10);
input.left = new TreeNode(5);
input.right = new TreeNode(15);
input.right.left = new TreeNode(6);
input.right.right = new TreeNode(20);
Assert.assertFalse(isValidBST(input));
}
public boolean isValidBST(TreeNode root) {
if (root == null) return true;
Stack<TreeNode> stack = new Stack<>();
List<TreeNode> list = new ArrayList<>();
while (root != null || stack.size() > 0) {
while (root != null) {
stack.push(root);
root = root.left;
}
if (stack.size() > 0) {
TreeNode treeNode = stack.pop();
list.add(treeNode);
root = treeNode.right;
}
}
for (int i = 1; i < list.size(); i++) {
if (list.get(i-1).val >= list.get(i).val) {
return false;
}
}
return true;
}
}
本文介绍了一种算法,用于验证给定的二叉树是否为有效的二叉搜索树。通过对二叉树进行遍历并检查每个节点值来确保其符合二叉搜索树的规定条件。
410

被折叠的 条评论
为什么被折叠?



