-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBInary_Tree_Introduction
80 lines (61 loc) · 1.58 KB
/
BInary_Tree_Introduction
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//The following code illustrates the construction of a simple binary tree
#include<stdio.h>
#include<stdlib.h>
// a structure indicating the basic structure of every node of the tree.
struct node
{
int data;
struct node *left;
struct node *right;
};
//newNode() method allocates a new node with the given data and NULL left and right pointers.
struct node* newNode(int data)
{
// Allocating memory to the new node
struct node* node = (struct node*)malloc(sizeof(struct node));
// Assign data to this node
node->data = data;
//printing the data to ensure the proper implementation i.e. just for verifying purposes.
printf("\nnew node created with data %d",data);
// Initialize left and right children of node as NULL
node->left = NULL;
node->right = NULL;
return(node);
}
//driver program
int main()
{
struct node *temp; //a temp node for traversing along the tree
// Now create root node with data 1
struct node *root = newNode(1);
/* following is the tree after above statement
1
/ \
NULL NULL
*/
//creating new nodes to left and right of root
root->left = newNode(2);
root->right = newNode(3);
/* 2 and 3 become left and right children of 1
1
/ \
2 3
/ \ / \
N N N N // here N stands for NULL
*/
//Make temp point to the left child of root
temp = root->left;
//creating a new node as left child of temp i.e. left of left of root
temp->left = newNode(4);
/* 4 becomes left child of 2
1
/ \
2 3
/ \ / \
4 N N N
/ \
N N
*/
return 0;
}
//Hope this makes clear on how to create a binary tree :)