-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOddEvenNodes.java
More file actions
116 lines (102 loc) · 2.67 KB
/
OddEvenNodes.java
File metadata and controls
116 lines (102 loc) · 2.67 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import java.util.LinkedList;
import java.util.Queue;
class BST {
public Node root;
private class Node {
public Node left;
public Node right;
public int data;
Node(int d) {
this.right = null;
this.left = null;
this.data = d;
}
}
BST() {
this.root = null;
}
private Node add(Node root, int v) {
if (root == null)
return new Node(v);
if (root.data > v)
root.left = add(root.left, v);
else
root.right = add(root.right, v);
return root;
}
public Node getroot() {
return this.root;
}
public void add(int v) {
this.root = add(this.root, v);
}
public int diff() {
Queue<Node> q = new LinkedList<>();
Node r = this.root;
q.add(r);
q.add(null);
int level = 1;
int even = 0, odd = 0;
while (!q.isEmpty()) {
Node temp = q.remove();
if (temp == null) {
level++;
if (q.isEmpty())
break;
q.add(null);
} else {
if (level % 2 == 0) {
even += temp.data;
} else {
odd += temp.data;
}
if (temp.left != null)
q.add(temp.left);
if (temp.right != null)
q.add(temp.right);
}
}
System.out.println(even + " " + odd);
return odd - even;
}
public void printLevel() {
Queue<Node> q = new LinkedList<>();
Node r = this.root;
q.add(r);
q.add(null);
while (!q.isEmpty()) {
// System.out.println("`SIZE: " + q.size());
Node temp = q.remove();
if (temp == null) {
System.out.println();
System.out.println("-------------");
if (q.isEmpty())
break;
q.add(null);
} else {
System.out.print(temp.data + " ");
if (temp.left != null)
q.add(temp.left);
if (temp.right != null)
q.add(temp.right);
}
}
}
}
public class OddEvenNodes {
public static void main(String[] args) {
BST tree = new BST();
tree.add(4);
tree.add(7);
tree.add(12);
tree.add(15);
tree.add(3);
tree.add(5);
tree.add(14);
tree.add(18);
tree.add(16);
tree.add(17);
tree.printLevel();
System.out.println(tree.diff());
}
}