What Is A Binary Tree?: Root Node. Nodes With Children Are Parent Nodes, and The Child Nodes Contain References To
What Is A Binary Tree?: Root Node. Nodes With Children Are Parent Nodes, and The Child Nodes Contain References To
What Is A Binary Tree?: Root Node. Nodes With Children Are Parent Nodes, and The Child Nodes Contain References To
A normal tree has no restrictions on the number of children each node can have. Binary trees,
on the other hand, can have at most two children for each parent. Every node contains a 'left'
reference, a 'right' reference, and a data element. The topmost node in the tree is called the
root node. Nodes with children are parent nodes, and the child nodes contain references to
their parents. A node with no children is called a leaf node. Thus, each node in a binary tree can
have either 0, 1 or 2 children as shown in Figure 1.
There are three different types of binary trees that will be discussed in this lesson:
Full binary tree: Every node other than leaf nodes has 2 child nodes.
Complete binary tree: All levels are filled except possibly the last one, and all nodes are
filled in as far left as possible.
Perfect binary tree: All nodes have two children and all leaves are at the same level.
We can represent a tree node structure in the C programming language. Consider an example that
consists of a node with integer data. We can then add to this to create a simple binary tree with four
nodes:
1. struct node
2. {
3. int data;
4. struct node *left;
5. struct node *right;
6. };
7. /* newNode() allocates a new node with the given data and NULL left and
8. right pointers. */
9. struct node* newNode(int data)
10. {
11. // Allocate memory for new node
12. struct node* node = (struct node*)malloc(sizeof(struct node));
13. // Assign data to this node
14. node->data = data;
15. // Initialize left and right children as NULL
16. node->left = NULL;
17. node->right = NULL;
18. return(node);
19. }
20. int main()
21. {
22. /*create root*/
23. struct node *root = newNode(1);
24. root->left = newNode(2);
25. root->right = newNode(3);
26. root->left->left = newNode(4);
27. getchar();
28. return 0;
29. }