List the nodes of a binary tree? C programming language

Asked By 0 points N/A Posted on -
qa-featured

Hi everyone, how can I write a program in the C programming language so that it can list the nodes of a binary tree? The list should start with the root, then the nodes at depth one followed by nodes at depth two and so forth. How can I go about this cause? Thanks.

SHARE
Answered By 5 points N/A #82071

List the nodes of a binary tree? C programming language

qa-featured

Hi S Susan
Building a Binary Tree in C Programming Language is very simple. You just need to learn the Binary Tree and their concept. After that you can easily create a C Program for Binary Tree. A binary tree is a very useful data-structure, it allows efficient insertion, searching and deletion in a sorted list.
Tree Concept: tree
empty
node left-branch right-branch

left-branch
tree

right-branch
tree

Program:
#include<stdlib.h>
#include<stdio.h>

struct tree_el {
int val;
struct tree_el * right, * left;
};

typedef struct tree_el node;

void insert(node ** tree, node * item) {
if(!(*tree)) {
*tree = item;
return;
}
if(item->val<(*tree)->val)
insert(&(*tree)->left, item);
else if(item->val>(*tree)->val)
insert(&(*tree)->right, item);
}

void printout(node * tree) {
if(tree->left) printout(tree->left);
printf("%dn",tree->val);
if(tree->right) printout(tree->right);
}

void main() {
node * curr, * root;
int i;

root = NULL;

for(i=1;i<=10;i++) {
curr = (node *)malloc(sizeof(node));
curr->left = curr->right = NULL;
curr->val = rand();
insert(&root, curr);
}

printout(root);
}

Thank You

Related Questions