logo CodeStepByStep logo

construct

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

Write a method named construct that accepts an integer n as a parameter and that constructs a new tree of integers with n nodes numbered 0 through (n - 1) such that an in-order traversal of the tree will produce the values in sequential order. The tree should be balanced in that the number of values in any node's left subtree should always be within one of the number of values in its right subtree. If there is an extra value in one of a node's two subtrees, it should appear in the right subtree.

For example, the call of construct(7) should produce the first tree shown below and return a reference to its root as a TreeNode. If the call had been construct(10), the tree's state should be that of the second tree shown below.

Call Tree
construct(7)
(3 (1 (0) (2)) (5 (4) (6)))
construct(10)
(4 (1 (0) (2 / (3))) (7 (5 / (6)) (8 / (9))))

You should return an empty (null) tree if passed a value of 0 and should generate an IllegalArgumentException if passed a negative value.

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.