need help with binary tree

you are to develop some binary trees routind that will handle single work. the binary tree is to be maintain as an ordered tree.
the routins you need are
add
delete
search
traverse
using the following sequences word test your program
add kindness rascal structures
inorder
preorder
search
delete
#include <stdio.h>

#include <stdlib.h>

using namespace std;
/* A binary tree node has data, pointer to left child

and a pointer to right child */

struct node

{

int data;

struct node* left;

struct node* right;

};

/* Function to get the count of leaf nodes in a binary tree*/

unsigned int getLeafCount(struct node* node)

{

if(node == NULL)

return 0;

if(node->left == NULL && node->right==NULL)

return 1;

else

return getLeafCount(node->left)+

getLeafCount(node->right);

}

/* Helper function that allocates a new node with the

given data and NULL left and right pointers. */

struct node* newNode(int data)

{

struct node* node = (struct node*)

malloc(sizeof(struct node));

node->data = data;

node->left = NULL;

node->right = NULL;

return(node);

}

/*Driver program to test above functions*/

int main()

{

/*create a tree*/

struct node *root = newNode(1);

root->left = newNode(2);

root->right = newNode(3);

root->left->left = newNode(4);

root->left->right = newNode(5);

/*get leaf count of the above created tree*/



getchar();

return 0;

}
When you create the tree in your main program, you're creating it out of order. If you add 1,2,3,4,5 to a binary tree, you will get 1 in the root, 2 in root->right, 3 in root->right->right, 4 in root->right-right-right and 5 in root->right->right->right->right.

You should use classes for this. Something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class node {
public:
    node(int v); // construct a node with value and null right/left pointers
    ~node();     // destroy node and delete children
    int val;
    node *left, *right;
};

class tree {
public:
    tree();
    node *root;
    void Add(int val);  // add val to the tree
    bool Delete(int val);; // delete val from tree, returns true if it was present
    // etc. 


Then your code to create the tree looks like this:
1
2
3
4
5
6
tree mytree;
mytree.Add(1);
mytree.Add(2);
mytree.Add(3);
mytree.Add(4);
mytree.Add(5);

Topic archived. No new replies allowed.