logo CodeStepByStep logo

sequential

Language/Type: C++ binary trees pointers recursion

Write a function named sequential that accepts a single int parameter N and returns a pointer to a TreeNode that is the root of a tree with N nodes, with data fields 0 through N - 1, such that the in-order traversal of the tree has data fields in increasing order, and the tree is balanced. (The number of nodes in any left subtree should be within one of the number of nodes in the corresponding right subtree.) If there are an odd number of nodes, put the extra node in the right subtree. If N is 0, return a null tree. If N is negative, throw an integer exception.

For example, the call of sequential(10); must create the following tree and return the pointer to the root 4 node:

(4 (1 (0) (2 / (3))) (7 (5 / (6)) (8 / (9))))

Constraints: You must implement your function recursively and without using loops. Do not use any auxiliary data structures to solve this problem (no array, vector, stack, queue, string, etc).

Assume that you are using the BinaryTreeNode structure as defined below:

struct BinaryTreeNode {
    int data;
    BinaryTreeNode* left;
    BinaryTreeNode* right;
};
Function: Write a C++ function as described, not a complete program.

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.