-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIsBSTAndCBT.java
More file actions
92 lines (82 loc) · 2.55 KB
/
Copy pathIsBSTAndCBT.java
File metadata and controls
92 lines (82 loc) · 2.55 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package tree;
import org.junit.Test;
import utils.TreeNodeUtil;
import java.util.LinkedList;
import java.util.Stack;
/**
* @Author: wei1
* @Date: Create in 2018/11/22 15:25
* @Description: 判断是不是二叉搜索树
* 当前节点为null就弹出来,往右移
*/
public class IsBSTAndCBT {
//思路就是通过中序遍历,如果是递增的就是BST
public static boolean isBST(TreeNode head) {
if (head == null) {
//空树也是的
return true;
}
Stack<TreeNode> stack = new Stack<>();
int min = Integer.MIN_VALUE;
while (!stack.isEmpty() || head != null) {
if (head != null) {
stack.add(head);
head = head.left;
} else {
head = stack.pop();
System.out.print(head.val + " ");
if (min < head.val) {
min = head.val;
} else {
return false;
}
head = head.right;
}
}
return true;
}
public static boolean isCBT(TreeNode head) {
if (head == null) {
//空树也是完全二叉树
return true;
}
boolean leaf = false;
//层次遍历使用queue
LinkedList<TreeNode> linkedList = new LinkedList<>();
linkedList.push(head);
while (!linkedList.isEmpty()) {
head = linkedList.poll();
System.out.print(head.val+" ");
if ((head.left == null && head.right != null) ||
leaf && (head.left != null || head.right != null)) {
return false;
}
//在这里要记住push和offer、add的区别
if (head.left != null) {
linkedList.offer(head.left);
}
if (head.right != null) {
linkedList.offer(head.right);
} else {
leaf = true;
}
}
return true;
}
@Test
public void test() {
tree.TreeNode head = TreeNodeUtil.getTree();
System.out.println(isBST(head));
}
public static void main(String[] args) {
TreeNode head = new TreeNode(4);
head.left = new TreeNode(2);
head.right = new TreeNode(6);
head.left.left = new TreeNode(1);
head.left.right = new TreeNode(3);
head.right.left = new TreeNode(5);
tree.PrintBinaryTree.printTree(head);
System.out.println(isBST(head));
System.out.println(isCBT(head));
}
}