Trees in C
Trees in C
CSE 2541
Matt Boggus
Tree definition
Recursively defined data structure
Tree (in general)
Empty
Data + a specific number of subtrees
Binary tree
Empty
Data + left subtree + right subtree
struct btnode {
int data;
struct btnode *left;
struct btnode *right;
};
What is this?
struct treenode {
int data;
struct treenode *mynode;
};
Creating a tree
struct btnode *root;
struct btnode *mynode =
(struct btnode *) malloc (sizeof(struct
btnode));
root = mynode;
// use root to access the tree, like head for a
linked list
Tree termination
NULL pointers
NULL are not
btnodes, but the
value of their
parents left and
right pointers
NULL data
-1 are btnodes,
whose left and
right btnodes are
uninitialized
Assumption: -1 is never
valid data in the tree
Creating nodes
struct node * NewNode(int data) {
struct node *mynode = (struct node *) malloc (sizeof(struct
node));
mynode->data = data;
mynode->left = NULL;
mynode->right = NULL;
return(node);
}
Order in the
array by level
in the tree
Order in the
array by level
in the tree