forked from xiaoningning/java-algorithm-2010
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNode.java
More file actions
71 lines (63 loc) · 1.56 KB
/
Node.java
File metadata and controls
71 lines (63 loc) · 1.56 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
import java.util.LinkedList;
import java.util.Queue;
/**
* a node class for tree
*/
public class Node {
public int value;
public Node left;
public Node right;
public Node(int v) {
value = v;
left = null;
right = null;
}
public boolean insert(Node n) {
if (n == null)
return false;
if (value >= n.value) {
if (left == null)
left = n;
else
left.insert(n);
} else {
if (right == null)
right = n;
else
right.insert(n);
}
return true;
}
public int size() {
int size = 0;
if (left != null) {
size += left.size();
}
if (right != null) {
size += right.size();
}
return size + 1;
}
public void printBT(){
Queue<Node> current = new LinkedList<Node>();
Queue<Node> next = new LinkedList<Node>();
current.add(this);
System.out.println(this.value);
while (!current.isEmpty()){
Node n = current.poll();
if(n.left != null){
System.out.print(n.left.value + " ");
next.add(n.left);
}
if(n.right != null){
System.out.print(n.right.value + " ");
next.add(n.right);
}
if(current.isEmpty()){
current.addAll(next);
next.clear();
System.out.println();
}
}
}
}