-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncodingTree.java
More file actions
72 lines (63 loc) · 1.84 KB
/
EncodingTree.java
File metadata and controls
72 lines (63 loc) · 1.84 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
/**
* This class represents the encoding tree used in Huffman coding.
*/
public class EncodingTree {
private Node root;
/**
* Constructs an encoding tree with the specified root node.
*
* @param root The root node of the encoding tree.
*/
public EncodingTree(Node root) {
this.root = root;
}
/**
* Retrieves the root node of the encoding tree.
*
* @return The root node of the encoding tree.
*/
public Node getRoot() {
return root;
}
/**
* Gets the maximum depth of the encoding tree.
*
* @return The maximum depth of the encoding tree.
*/
public int getDepth() {
return getDepth(this.root);
}
/**
* Recursively calculates the depth of a node in the tree.
*
* @param node The current node being examined.
* @return The depth of the node.
*/
private int getDepth(Node node) {
if (node == null) {
return 0;
} else {
int leftDepth = getDepth(node.getLeft());
int rightDepth = getDepth(node.getRight());
return Math.max(leftDepth, rightDepth) + 1;
}
}
/**
* Prints the structure of the encoding tree in a hierarchical manner.
*
* @param node The current node being visited.
* @param level The current level in the tree hierarchy.
*/
public void printTree(Node node, int level) {
if (node == null)
return;
for (int i = 0; i < level; i++)
System.out.print(" ");
if (node.getCharacter() != '\0')
System.out.println(node.getCharacter() + ":" + node.getFrequency());
else
System.out.println("Value:" + node.getFrequency());
printTree(node.getLeft(), level + 1);
printTree(node.getRight(), level + 1);
}
}