-
Notifications
You must be signed in to change notification settings - Fork 13
/
Solution098.java
55 lines (47 loc) · 1.13 KB
/
Solution098.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package algorithm.leetcode;
import java.util.ArrayList;
import java.util.List;
/**
* @author: mayuan
* @desc: 验证二叉搜索树
* @date: 2019/02/19
*/
public class Solution098 {
/**
* 二叉搜索树的中序遍历序列是递增的
* 左子树的所有节点值都小于该节点
* 右子树的所有节点值都大于该节点
*
* @param root
* @return
*/
public boolean isValidBST(TreeNode root) {
if (null == root) {
return true;
}
List<Integer> ans = new ArrayList<>();
inOrder(root, ans);
for (int i = 1; i < ans.size(); ++i) {
if (ans.get(i - 1) >= ans.get(i)) {
return false;
}
}
return true;
}
public void inOrder(TreeNode node, List<Integer> result) {
if (null == node) {
return;
}
inOrder(node.left, result);
result.add(node.val);
inOrder(node.right, result);
}
private class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}