logo CodeStepByStep logo

writeTree

Language/Type: Java binary trees

Write a method named writeTree that prints a binary tree of integers in a specific format. Your method accepts as its parameter a TreeNode that refers to the root of the tree. You are to perform a pre-order traversal of the tree, producing exactly one line of output for each node. Each output line should begin with a code indicating the type of node from the following table, followed by the data in the node:

Code Node Type
0 leaf node (no children)
1 branch node with left child only
2 branch node with right child only
3 branch node with left and right children

For example, suppose a variable named tree refers to the root of the following tree:

(7 (9 (5)) (8 (4 / (9)) (6)))

The call of writeTree(tree); would produce the following console output:

3 7
1 9
0 5
3 8
2 4
0 9
0 6

Assume that you are interacting with TreeNodes as defined below:

public class TreeNode {
    public int data;
    public TreeNode left;
    public TreeNode right;
    
    public TreeNode() { ... }
    public TreeNode(int data) { ... }
    public TreeNode(int data, TreeNode left, TreeNode right) { ... }
}
Method: Write a Java method as described, not a complete program or class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.