- Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathValidate_Binary_Search_Tree.java
38 lines (30 loc) · 958 Bytes
/
Validate_Binary_Search_Tree.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//Leetcode 98. Validate Binary Search Tree
//Question - https://leetcode.com/problems/validate-binary-search-tree/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
classSolution {
publicbooleanisValidBST(TreeNoderoot) {
Stack<TreeNode> stk = newStack<TreeNode>();
TreeNodeprev = null;
while(root!=null || stk.size()!=0){
//keep going left
while(root!=null){
stk.push(root);
root = root.left;
}
root = stk.pop();
//if(prev!=null) System.out.println(prev.val+" "+root.val);
if(prev!=null && prev.val>=root.val) returnfalse;
prev = root;
root = root.right;
}
returntrue;
}
}