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 TreeNode
s 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) { ... }
}