- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathvalidateBinarySearchTree.java
More file actions
Latest commit
34 lines (29 loc) · 977 Bytes
/
Copy pathvalidateBinarySearchTree.java
File metadata and controls
34 lines (29 loc) · 977 Bytes
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
//判断一颗二叉树是否是一个合法的binary search tree
//考虑当前节点左子树的右子树,这个节点需要比它的父亲节点大但要比它的爷爷节点小,所以要新引入一个函数
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
publicclassSolution {
booleanvalidChild(TreeNodenode, intmin, intmax) {
if(node==null) {
returntrue;
}
if(node.val>min&&node.val<max) {
returnvalidChild(node.left,min,node.val)&&validChild(node.right,node.val,max);
} else {
returnfalse;
}
}
publicbooleanisValidBST(TreeNoderoot) {
if(root==null) {
returntrue;
}
returnvalidChild(root.left,Integer.MIN_VALUE,root.val)&&validChild(root.right,root.val,Integer.MAX_VALUE);
}
}