Here are some exercises for toning your C muscles. NOTE: In the below text:
#define IF_WRONG_CORRECT_IT "Is there something wrong with this code? How would you correct it?"
Binary Trees
Some of the questions have been copied from Binary Trees from Stanford University. Please visit their web-site to find more problems.
- EASY: Write a recursive function size(TreeNode* root) that prints the number of elements in the tree.
- EASY: Write a recursive function maxDepth(TreeNode* root) that prints the maximum depth of the tree.
- EASY: Write an iterative function to insert an element into a binary search tree.
- EASY: Write a recursive function to search an element into a binary search tree.
- MEDIUM: Write a recursive function mirror(TreeNode* root) that
swaps the left and right pointers of the tree. Below trees provide an example input and output for mirror()
4 4
/ \ / \
2 5 5 2
/ \ / \
1 3 3 1
INPUT TREE OUTPUT TREE
-
MEDIUM: Write a function insert(TreeNode** root, int element)
for inserting an element into a Binary Search Tree root.
-
MEDIUM: Write a recursive function for in-order tree traversal (google "inorder traversal" if you do not know what inorder means).
Quiz
- Write a C program bstoi(char* str) that takes a binary string and converts it into an integer. The binary string is a string that has only 1s and 0s (for example, "0101001001").
- Extend the above program. Now the user will type a binary password and a binary mask. Store the binary password and binary mask into ints (using bstoi() function), and then display only the digits where mask bit is "1"