LeetCode --- 驗證二叉搜尋樹
阿新 • • 發佈:2019-02-15
給定一個二叉樹,判斷其是否是一個有效的二叉搜尋樹。
一個二叉搜尋樹具有如下特徵:
節點的左子樹只包含小於當前節點的數。
節點的右子樹只包含大於當前節點的數。
所有左子樹和右子樹自身必須也是二叉搜尋樹。
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;
}
}