Practice Exercise

Tree is Size Balanced

Your task is to write a function, treeIsSizeBalanced, that determines whether a given tree is size balanced. A tree is size balanced if, for every node, the difference in size (i.e., number of nodes) between its left and right subtrees does not exceed 1. The function should return true if the tree is size balanced, and false otherwise.

Download

While in your practice exercises directory, run the following command:

unzip /web/cs2521/practice-exercises/trees/treeIsSizeBalanced/downloads/treeIsSizeBalanced.zip

If you're working at home, download treeIsSizeBalanced.zip by clicking on the above link and then unzip the downloaded file.

Files

tree.c Contains code for reading and printing a binary tree
tree.h Contains the definition of the binary tree data structure and function prototypes
testTreeIsSizeBalanced.c Contains the main function, which reads in a binary tree from standard input, calls treeIsSizeBalanced, and prints out the result.
treeIsSizeBalanced.c Contains treeIsSizeBalanced, the function you must implement
Makefile A makefile to compile your code
tests/ A directory containing the inputs and expected outputs for some basic tests
autotest A script that uses the tests in the tests directory to autotest your solution. You should only run this after you have tested your solution manually.

Examples

./testTreeIsSizeBalanced
Enter the preorder traversal of the tree: 3 2 1 4 5
Enter the in-order traversal of the tree: 1 2 3 4 5

Tree:

    3
   / \
  2   4
 /     \
1       5

treeIsSizeBalanced returned TRUE
./testTreeIsSizeBalanced
Enter the preorder traversal of the tree: 1 2 4 7 5 3 6
Enter the in-order traversal of the tree: 7 4 2 5 1 6 3

Tree:

        1
       / \
      /   \
     /     \
    2       3
   / \     /
  4   5   6
 /
7

treeIsSizeBalanced returned FALSE
./testTreeIsSizeBalanced
Enter the preorder traversal of the tree: 
Enter the in-order traversal of the tree: 

Tree:

X

treeIsSizeBalanced returned TRUE

Testing

You can compile and test your function using the following commands:

make                                      # compiles the program
./testTreeIsSizeBalanced                  # tests with manual input, outputs to terminal
./testTreeIsSizeBalanced < input-file     # tests with input from a file, outputs to terminal
./testTreeIsSizeBalanced < tests/01.in    # for example, tests with input from tests/01.in
                                            # (then manually compare with tests/01.exp)

After you have manually tested your solution, you can autotest it by running ./autotest. This will run some basic tests on your program, as well as check for memory leaks/errors.

It is possible to devise your own tests by creating your own input files. See the existing input files for examples. Note that you will need to check the output yourself.

Follow up: Can you solve this in \( O(n) \) time?