-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidateBST.java
More file actions
57 lines (55 loc) · 1.69 KB
/
validateBST.java
File metadata and controls
57 lines (55 loc) · 1.69 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public class Solution {
int previous;
public boolean isValidBST(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
previous=Integer.MIN_VALUE;
return b(root);
}
public boolean b(TreeNode root) {
if(root==null) return true;
if(!b(root.left))
return false;
if(root.val<=previous)
return false;
previous=root.val;
return b(root.right);
}
}
public class Solution {
public boolean isValidBST(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if(root==null) return true;
boolean left,right;
if(root.left==null||root.left.val<root.val)
left = isValidBST(root.left);
else
return false;
if(!left) return false;
if(root.right==null||root.right.val>root.val)
right = isValidBST(root.right);
else
return false;
return left&&right;
return bst(root);
}
public boolean bst(TreeNode root) {
if(root==null) return true;
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.add(root);
while(!q.isEmpty()) {
TreeNode node = q.poll();
if(node.left!=null)
if(node.left.val<node.val)
q.add(node.left);
else return false;
if(node.right!=null)
if(node.right.val>node.val)
q.add(node.right);
else return false;
}
return true;
}
}
http://www.geeksforgeeks.org/a-program-to-check-if-a-binary-tree-is-bst-or-not/