Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a method called makePerfect that adds nodes until the binary tree is a per

ID: 3729343 • Letter: W

Question

Write a method called makePerfect that adds 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, and all of the leaves are at the same level. Each new node you add to the tree
should store the value 0. For example, if a variable t refers to reference tree #2, then the call t.makePerfect();

Explanation / Answer

Following is the solution:

//makePerfect function call

public void makePerfect() {

overallRoot = makePerfect(overallRoot, height());

}

// implementation of makePerfect

public IntTreeNode makePerfect(IntTreeNode root, int height) {

//if root is null then root is new node   

if (root == null) {

root = new IntTreeNode(0);

}

//if height is 0 then return null

if (height == 0) {

return null;

//else add node to the left or right for baalancing

} else {

root.left = makePerfect(root.left, height - 1);

root.right = makePerfect(root.right, height - 1);

return root;

}

}

//height function call

public int height() {

return height(overallRoot);

}

//height function implementation

private int height(IntTreeNode root) {

if (root == null) {

return 0;

} else {

return 1 + Math.max(height(root.left), height(root.right));

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote