logo CodeStepByStep logo

numberNodes

Language/Type: Java binary trees

Write a method named numberNodes that changes the data stored in a binary tree, assigning sequential integers starting with 1 to each node so that a pre-order traversal will produce the numbers in order (1, 2, 3, etc.). Your method accepts as its parameter a TreeNode referring to the root of the tree. For example, suppose a variable named tree refers to the following tree:

(7 (3 (9) (2)) (9 / (0)))

The call of numberNodes(tree) would overwrite the existing data assigning the nodes values from 1 to 6 so that a pre-order traversal of the tree would produce 1, 2, 3, 4, 5, 6:

(1 (2 (3) (4)) (5 / (6)))

Your method should also return a count of how many nodes were in the tree; in this case, 6.

You are not to change the structure of the tree. You are simply changing the values stored in the data fields.

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.