Share
Explore BrainMass

Implementing Operations on Binary Trees

Consider the following definition of a Binary Tree structure:

typedef struct BTnode *node;
struct BTnode {
int key;
node left;
node right;
};

1. Write a function in C programming language that can find and return the height of a Binary Tree.
2. Write a function in C programming language that can find and return the cost of the most expensive path from the root of a Binary Tree to a leaf.
3. Write a function in C programming language that finds if a particular Binary Tree is balanced.

More explanations are provided in the attached document.

Attachments

Solution Preview

Please find attached 450363.c containing just the function implementations. Code has been commented well, but even without that logic is quite clear as it is based on recursion. This implementation makes use of an auxiliary function min_height in determining whether a tree is balanced as per the given criteria or not.

#include <stdio.h>

/* Binary Tree structure */

typedef struct BTnode *node;
struct BTnode {
int key;
node left;
node right;
};

/*
* This function finds and returns the height of a Binary Tree.
*
* The height of a binary tree is the length of the longest path from root of
* the Binary Tree to a leaf.
*
* This implementation considers that the height of a null tree is 0 and that of
* a single node tree is 1.
*/

int height (node root)
{
if (root == (node) NULL)
return 0;
else
{
...

Solution Summary

Attached solution contains just the function implementations. Code has been commented well, but even without that logic is quite clear as it is based on recursion. This implementation makes use of an auxiliary function min_height in determining whether a tree is balanced as per the given criteria or not.

$2.19