Reputation:
I need to do an inorder traversal of a binary search tree, and I need to print all the nodes and the level they're at, but I can't think of a way to do this.
For example:
If I have this bst, the output would be:
4 #1
5 #0
9 #1
7 #2
10 #2
18 #3
This is so far what I got:
This is the struct I'm using:
struct tree {
int number;
tree *izq;
tree *der;
};
typedef struct tree *bst;
And this is the function I'm trying to implement:
void printTree(bst node) {
if (node==NULL) {
return;
}
else {
if (node->left != NULL) {
printTree(node->left);
}
printf("%d", node->number);
if (node->right !=NULL) {
printTree(node->right);
}
}
}
Does anyone have any ideas? Thank you :)
Upvotes: 0
Views: 285
Reputation: 32586
warning
struct tree {
int number;
tree *izq;
tree *der;
};
must be
struct tree {
int number;
struct tree *izq;
struct tree *der;
};
because the case where node is NULL is checked at the beginning you can simplify :
void printTree(bst node) {
if (node != NULL) {
printTree(node->izq);
printf("%d", node->number);
printTree(node->der);
}
}
adding the level:
void printTree(bst node, int lvl) {
if (node != NULL) {
printTree(node->izq, lvl + 1);
printf("%d #%d\n", node->number, lvl);
printTree(node->der, lvl + 1);
}
}
and you call at the root level with level 0
Making a full program :
#include <stdio.h>
#include <stdlib.h>
struct tree {
int number;
struct tree *izq;
struct tree *der;
};
typedef struct tree *bst;
void printTree(bst node, int lvl) {
if (node != NULL) {
printTree(node->izq, lvl + 1);
printf("%d #%d\n", node->number, lvl);
printTree(node->der, lvl + 1);
}
}
struct tree * mk(int v, struct tree * l, struct tree * r)
{
struct tree * t = malloc(sizeof(struct tree));
t->number = v;
t->izq = l;
t->der = r;
return t;
}
int main()
{
struct tree * r = mk(5, mk(4, NULL, NULL), mk(9, mk(7, NULL, NULL), mk(10, NULL, mk(18, NULL, NULL))));
printTree(r, 0);
}
Compilation an execution :
pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out
4 #1
5 #0
7 #2
9 #1
10 #2
18 #3
Upvotes: 0
Reputation: 85
I implemented this with Java, but I think you can easily convert it to C:
private static void printWithLevels(TreeNode node) {
printWithLevels(node, 0);
}
private static void printWithLevels(TreeNode node, int level) {
if (node == null) return;
System.out.println(node.value + "(" + level + ")");
printWithLevels(node.left, level + 1);
printWithLevels(node.right, level + 1);
}
For my solution to be complete, this is my simple/quick implementation of TreeNode:
private static class TreeNode {
int value;
TreeNode left;
TreeNode right;
TreeNode(int value, TreeNode left, TreeNode right) {
this.value = value;
this.left = left;
this.right = right;
}
}
Upvotes: 1