I am suppose to write a method makePerfect that could be added to the IntTree class. The method should add nodes until the binary tree is a "perfect" tree. A perfect binary tree is one where all leaves are at the same level. Another way of thinking of it is that you are adding dummy nodes to the tree until every path from the root to a leaf is the same length. A perfect tree's shape is exactly triangular and every branch node has exactly two children. Each node you add to the tree should store the value 0.
An example of before and after calls :
my code works for these cases:
but fails others. With this method, there is a helper method that is included that we may only call once.
// WRITE YOUR CODE HERE
public void makePerfect() {
overallRoot = makePerfect(overallRoot, 1);
}
private IntTreeNode makePerfect(IntTreeNode root, int lvl) {
if(root != null) {
if( lvl < height(root) ) {
if(root.left == null && root.right != null) {
root.left = new IntTreeNode(0);
root.left = makePerfect(root.left, lvl + 1);
root.right = makePerfect(root.right, lvl +1);
}if(root.right == null && root.left != null) {
root.right = new IntTreeNode(0);
root.right = makePerfect(root.right, lvl +1);
root.left =makePerfect(root.left, lvl +1);
}else if ( root.left == null && root.right == null) {
root.left = new IntTreeNode(0);
root.right = new IntTreeNode(0);
lvl++;
}else {
root.left = makePerfect(root.left, lvl +1);
root.right = makePerfect(root.right, lvl +1);
}
}
}
return root;
}
// LEAVE THESE METHODS HERE, TO USE AS HELPERS
public int height() {
return height(overallRoot);
}
private int height(IntTreeNode root) {
if (root == null) {
return 0;
} else {
return 1 + Math.max(height(root.left), height(root.right));
}
}
What cases am I not testing for ? Been stuck on this for a while, any help would be greatly appreciated.
My code fails these cases:
My output is the same as the "name" column, it is not recursing correctly.