Lab 6 – Binary Trees
Part 1 – A binary tree of integers¶
Task 1 – Nodes and a first tree¶
class Node {
int data;
Node left, right;
Node(int data) {
this.data = data;
left = right = null;
}
}Write buildTree(), which builds this tree by linking nodes by hand and returns its root:
1
/ \
2 3
/ \ /
4 5 6
/ \
7 8Solution
static Node buildTree() {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.left.right.left = new Node(7);
root.right.left = new Node(6);
root.right.left.right = new Node(8);
return root;
}Task 2 – The three recursive traversals¶
Print the tree in preorder (root, left, right), inorder (left, root, right) and postorder (left, right, root). The three methods differ only in where the root is printed.
static void preorder(Node p) { /* ToDo */ }
static void inorder(Node p) { /* ToDo */ }
static void postorder(Node p) { /* ToDo */ }Solution
static void preorder(Node p) {
if (p == null) return;
System.out.print(p.data + " ");
preorder(p.left);
preorder(p.right);
}
static void inorder(Node p) {
if (p == null) return;
inorder(p.left);
System.out.print(p.data + " ");
inorder(p.right);
}
static void postorder(Node p) {
if (p == null) return;
postorder(p.left);
postorder(p.right);
System.out.print(p.data + " ");
}Task 3 – Level-order traversal with a queue¶
Level order is not recursive: use the JDK queue Queue<Node> q = new ArrayDeque<>();.
Start with the root; repeatedly remove a node, print it and add its children.
static void levelOrder(Node root) {
// ToDo (offer, poll, isEmpty)
}Solution
static void levelOrder(Node root) {
if (root == null) return;
Queue<Node> q = new ArrayDeque<>();
q.offer(root);
while (!q.isEmpty()) {
Node p = q.poll();
System.out.print(p.data + " ");
if (p.left != null) q.offer(p.left);
if (p.right != null) q.offer(p.right);
}
}Task 4 – Size, height and leaves¶
Each method handles the empty tree (p == null), then combines the answers of the two
subtrees. The height of an empty tree is -1, so that a single node has height 0.
static int size(Node p) { /* ToDo */ }
static int height(Node p) { /* ToDo */ }
static int leaves(Node p) { /* ToDo */ }Solution
static int size(Node p) {
if (p == null) return 0;
return 1 + size(p.left) + size(p.right);
}
static int height(Node p) {
if (p == null) return -1; // so that a leaf has height 0
return 1 + Math.max(height(p.left), height(p.right));
}
static int leaves(Node p) {
if (p == null) return 0;
if (p.left == null && p.right == null) return 1;
return leaves(p.left) + leaves(p.right);
}Test your tree¶
Node root = buildTree();
System.out.print("preorder: "); preorder(root); System.out.println();
System.out.print("inorder: "); inorder(root); System.out.println();
System.out.print("postorder: "); postorder(root); System.out.println();
System.out.print("level order: "); levelOrder(root); System.out.println();
System.out.println("size " + size(root) + ", height " + height(root)
+ ", leaves " + leaves(root));Expected output:
preorder: 1 2 4 5 7 3 6 8
inorder: 4 2 7 5 1 6 8 3
postorder: 4 7 5 2 8 6 3 1
level order: 1 2 3 4 5 6 7 8
size 8, height 3, leaves 3Part 2 – Expression trees¶
Task 5 – Evaluate and print an expression tree¶
Leaves hold numbers; internal nodes hold an operator.
class ExprNode {
char op; // '+', '-', '*', '/' for an operator node
int value; // the number, for a leaf
ExprNode left, right;
ExprNode(int value) { this.value = value; } // a leaf
ExprNode(char op, ExprNode left, ExprNode right) { // an operator
this.op = op; this.left = left; this.right = right;
}
boolean isLeaf() { return left == null && right == null; }
}Write eval, which computes the value (a postorder computation: both subtrees first),
and toInfix, which prints the expression with all its parentheses (an inorder
traversal).
static int eval(ExprNode p) { /* ToDo */ }
static String toInfix(ExprNode p) { /* ToDo */ }Solution
static int eval(ExprNode p) {
if (p.isLeaf())
return p.value;
int a = eval(p.left); // postorder: children first
int b = eval(p.right);
switch (p.op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
default: return a / b;
}
}
static String toInfix(ExprNode p) { // inorder, with parentheses
if (p.isLeaf())
return String.valueOf(p.value);
return "(" + toInfix(p.left) + p.op + toInfix(p.right) + ")";
}Task 6 – Build an expression tree from postfix¶
This is the postfix evaluation of Lab 4, with a stack of trees instead of numbers: a
number pushes a one-node tree; an operator pops two trees (the first popped is the
right child) and pushes a new tree. Use Deque<ExprNode> st = new ArrayDeque<>();.
static ExprNode fromPostfix(String postfix) {
// ToDo
}Solution
static ExprNode fromPostfix(String postfix) {
Deque<ExprNode> st = new ArrayDeque<>(); // a stack of trees
for (String t : postfix.split(" ")) {
if (t.length() == 1 && "+-*/".contains(t)) {
ExprNode right = st.pop(); // popped first: the right child
ExprNode left = st.pop();
st.push(new ExprNode(t.charAt(0), left, right));
} else {
st.push(new ExprNode(Integer.parseInt(t)));
}
}
return st.pop();
}Test your expression trees¶
ExprNode e = new ExprNode('*',
new ExprNode('+', new ExprNode(3), new ExprNode(4)),
new ExprNode('-', new ExprNode(5), new ExprNode(2)));
System.out.println(toInfix(e) + " = " + eval(e));
ExprNode f = fromPostfix("6 5 2 3 + 8 * + 3 + *");
System.out.println(toInfix(f) + " = " + eval(f));Expected output:
((3+4)*(5-2)) = 21
(6*((5+((2+3)*8))+3)) = 288Part 3 – Use the JDK¶
Challenge 1 – Folder sizes in a general tree¶
A folder can have any number of children, so store them in an ArrayList<Folder>. Write
totalSize (a postorder sum) and show, which prints the tree indented by depth (a
preorder walk).
Solution
static class Folder {
String name;
long size; // own size (0 for a folder)
List<Folder> children = new ArrayList<>();
Folder(String name, long size) { this.name = name; this.size = size; }
Folder add(Folder child) { children.add(child); return this; }
}
static long totalSize(Folder f) { // postorder on a general tree
long sum = f.size;
for (Folder c : f.children)
sum += totalSize(c);
return sum;
}
static void show(Folder f, int depth) { // preorder, indented by depth
System.out.println(" ".repeat(depth) + f.name + " (" + totalSize(f) + " MB)");
for (Folder c : f.children)
show(c, depth + 1);
}Folder course = new Folder("course", 0)
.add(new Folder("slides", 0).add(new Folder("ch1.pdf", 10))
.add(new Folder("ch2.pdf", 15)))
.add(new Folder("notes.txt", 3))
.add(new Folder("labs", 0).add(new Folder("lab1.zip", 10)));
show(course, 0);Expected output:
course (38 MB)
slides (25 MB)
ch1.pdf (10 MB)
ch2.pdf (15 MB)
notes.txt (3 MB)
labs (10 MB)
lab1.zip (10 MB)Challenge 2 – How many nodes on each level?¶
Walk the tree with the depth as a parameter and count the nodes per depth in a
TreeMap<Integer, Integer>. count.merge(depth, 1, Integer::sum) adds 1 to the count of
depth (or puts 1 the first time).
Solution
static void widths(Node p, int depth, Map<Integer, Integer> count) {
if (p == null) return;
count.merge(depth, 1, Integer::sum); // one more node at this depth
widths(p.left, depth + 1, count);
widths(p.right, depth + 1, count);
}Map<Integer, Integer> count = new TreeMap<>(); // sorted by depth
widths(buildTree(), 0, count);
System.out.println(count);Expected output:
{0=1, 1=2, 2=3, 3=2}Challenge 3 – Rebuild a tree from its preorder and inorder sequences¶
The final-exam question of Chapter 6: inorder 5 13 6 7 8 10 41, preorder
10 13 5 6 8 7 41. The next preorder value is the root; its position in the inorder
sequence splits the left and right subtrees. A HashMap from value to inorder position
finds that split in , so the whole rebuild is . Print the postorder and the
level order of the result to check it.
Solution
static int next = 0; // position in pre[]
static Node build(int[] pre, Map<Integer, Integer> pos, int lo, int hi) {
if (lo > hi) return null;
Node root = new Node(pre[next++]);
int k = pos.get(root.data); // where the root is in inorder: O(1)
root.left = build(pre, pos, lo, k - 1);
root.right = build(pre, pos, k + 1, hi);
return root;
}int[] in = {5, 13, 6, 7, 8, 10, 41};
int[] pre = {10, 13, 5, 6, 8, 7, 41};
Map<Integer, Integer> pos = new HashMap<>();
for (int i = 0; i < in.length; i++)
pos.put(in[i], i);
Node t = build(pre, pos, 0, in.length - 1);
System.out.print("postorder: "); postorder(t); System.out.println();
System.out.print("level order: "); levelOrder(t); System.out.println();Expected output:
postorder: 5 7 8 6 13 41 10
level order: 10 13 41 5 6 8 7