logo CodeStepByStep logo

sequential

Language/Type: C++ binary trees pointers recursion
Author: Marty Stepp (on 2016/08/27)

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: 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;
    ...
}
Type your solution here:


This is a function problem. Write a C++ function as described. Do not write a complete program; just the function(s) above.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.

© Marty Stepp, all rights reserved.