logo CodeStepByStep logo

tighten

Language/Type: Java binary trees x=change(x)

Write a method named tighten that eliminates branch nodes that have only one child. Your method accepts as its parameter a TreeNode that refers to the root of the tree and returns the tree's new root. For example, suppose a variable named tree refers to the root of the following tree:

(2 (8 (7 (4) (1 / (3)))) (9 (6 / (0 (4) (5)))))

The call of tighten(tree) should modify the tree and return the root of the following:

(2 (7 (4) (3)) (0 (4) (5)))

The nodes that stored the values 8, 9, 6, and 1 have been eliminated because each had one child. When a node is removed, it is replaced by its child. This can lead to multiple replacements because the child might itself be replaced (as in the case of 9 which is replaced by 6 which is replaced by 0).

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.