I am heavily struggling with making this method that removes all branches with only one child. For instance, this:
+---+
| 2 |
___ +---+ ___
/ \
+---+ +---+
| 8 | | 9 |
+---+ +---+
/ /
+---+ +---+
| 7 | | 6 |
+---+ +---+
/ \ \
+---+ +---+ +---+
| 4 | | 1 | | 0 |
+---+ +---+ +---+
\ / \
+---+ +---+ +---+
| 3 | | 4 | | 5 |
+---+ +---+ +---+
becomes...
+---+
| 2 |
___ +---+ ___
/ \
+---+ +---+
| 7 | | 0 |
+---+ +---+
/ \ / \
+---+ +---+ +---+ +---+
| 4 | | 3 | | 4 | | 5 |
+---+ +---+ +---+ +---+
I'm not really looking for any exact code solutions, but I'm more interested on how to approach this. My idea is to search the next nodes to see if they have single child nodes. If so, I will remove that node and "reattach" it to to one after that. However, the node after—and so on—may also have only one child. That's where I'm stuck. Is this the right way to think about this problem? If not, how else should I approach this?
Here's my code that is heavily flawed (doesn't work yet; to get idea accross):
// post: eliminates all branches with one child
public void tighten() {
if (overallRoot == null || (overallRoot.left == null && overallRoot.right == null)) {
return; // If empty or just overallRoot
} else {
tighten(overallRoot);
}
}
// helper for tighten
private void tighten(IntTreeNode root) {
// checks right side first
if (root.right.left != null && root.right.right == null) { // if next right is empty
root.right = root.right.left;
tighten(root.right);
} else if (root.right.right != null && root.right.left == null) { // if next left is empty
root.right = root.right.right;
tighten(root.right);
}
// checks the left side
if (root.left.left != null && root.left.right == null) { // if next right is empty
root.left = root.left.left;
tighten(root.left);
} else if (root.left.right != null && root.left.left == null) { // if next left is empty
root.left = root.right.right;
tighten(root.left);
}
// If node with two children
if (root.left != null && root.right != null) {
tighten(root.left);
tighten(root.right);
}
}