-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem8.java
68 lines (56 loc) · 1.38 KB
/
Problem8.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
56
57
58
59
60
61
62
63
64
65
66
67
68
class Node
{
int data;
Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
class Count
{
int count = 0;
}
class BinaryTree
{
Node root;
Count ct = new Count();
boolean countSingleRec(Node node, Count c)
{
if(node == null)
return true;
boolean left = countSingleRec(node.left, c);
boolean right = countSingleRec(node.right, c);
if(left == false || right == false)
return false;
if(node.left != null && node.data != node.left.data)
return false;
if(node.right != null && node.data != node.right.data)
return false;
c.count++;
return true;
}
int countSingle()
{
return countSingle(root);
}
int countSingle(Node node)
{
countSingleRec(node, ct);
return ct.count;
}
}
public class Main
{
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.root = new Node(5);
tree.root.left = new Node(4);
tree.root.right = new Node(5);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(4);
tree.root.right.right = new Node(5);
System.out.println(" unival subtrees : " + tree.countSingle());
}
}