-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValidateBinaryTree.java
36 lines (32 loc) · 968 Bytes
/
ValidateBinaryTree.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
package brian;
/**
* Created by brian on 10/8/17.
*/
public class ValidateBinaryTree {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
private TreeNode prev = null;
public boolean isValidBST(TreeNode root) {
// return validate(root, null, null);
return isIncreasing(root);
}
private boolean validate(TreeNode n, Integer low, Integer high) {
if (n == null) return true;
return (low == null || n.val > low) && (high == null || n.val < high)
&& validate(n.left, low, n.val)
&& validate(n.right, n.val, high);
}
private boolean isIncreasing(TreeNode n) {
if (n == null) return true;
if (isIncreasing(n.left)) {
if (prev != null && n.val <= prev.val) return false;
prev = n;
return isIncreasing(n.right);
}
return false;
}
}