Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
59 lines (49 loc) · 1.54 KB

File metadata and controls

59 lines (49 loc) · 1.54 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
58
59
package Algorithms.tree;
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class IsValidBST {
public boolean isValidBST(TreeNode root) {
return isValidBSTHelp(root).isValidBST;
}
public ReturnType isValidBSTHelp(TreeNode root) {
ReturnType ret = new ReturnType(Integer.MAX_VALUE, Integer.MIN_VALUE, true);
if (root == null) {
return ret;
}
ReturnType left = isValidBSTHelp(root.left);
ReturnType right = isValidBSTHelp(root.right);
/* the left tree and the right tree should both be Valid BST.
And the value of the root should be in the middle.
*/
if (!left.isValidBST
|| !right.isValidBST
|| left.max >= root.val
|| right.min <= root.val
) {
ret.isValidBST = false;
return ret;
}
// get the min value of the tree;
ret.min = Math.min(left.min, root.val);
// get the max value of the tree, consider the right node may be null;
ret.max = Math.max(right.max, root.val);
return ret;
}
public class ReturnType {
int min;
int max;
boolean isValidBST;
ReturnType(int min, int max, boolean isValidBST) {
this.min = min;
this.max = max;
this.isValidBST = isValidBST;
}
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.