Presentation is loading. Please wait.

Presentation is loading. Please wait.

Tree data structure.

Similar presentations


Presentation on theme: "Tree data structure."— Presentation transcript:

1 Tree data structure

2 Binary Search Tree - Implementation
Struct Node{ int data; Node *left; Node *right; }; Nodes will be created in heap using malloc function

3 Binary Search Tree - Implementation
Struct Node{ int data; Node *left; Node *right; }; Nodes will be created in heap using malloc function

4 Binary Search Tree - Implementation in C

5 //To search an element in BST, returns true if element is found
#include<stdio.h> #include<stdlib.h> //Definition of Node for Binary search tree struct node { int data; struct node* left; struct node* right; }; // Function to create a new Node in heap struct node* GetNewNode(int data) { struct node* newNode = (struct node*)malloc(sizeof(struct node)); newNode->data = data; newNode->left = newNode->right = NULL; return newNode; //return the address of the newly created node } // To insert data in BST, returns address of root node struct node* Insert(struct node* root,int data) { if(root == NULL) { // empty tree root = GetNewNode(data); // if data to be inserted is lesser, insert in left subtree. else if(data <= root->data) { root->left = Insert(root->left,data); // else, insert in right subtree. else { root->right = Insert(root->right,data); return root; //To search an element in BST, returns true if element is found int Search(struct node* root,int data) { if(root == NULL) { return 0; } else if(root->data == data) { return 1; else if(data <= root->data) { return Search(root->left,data); else { return Search(root->right,data); int main() { struct node* root = NULL; // Creating an empty tree /*Evaluating the logic of the code*/ root = Insert(root,15); root = Insert(root,10); root = Insert(root,20); root = Insert(root,25); root = Insert(root,8); root = Insert(root,12); // Ask user to enter a number. int number; printf("Enter number be searched\n"); scanf("%d",&number); //If number is found, print "FOUND" if(Search(root,number) == 1) printf("Found\n"); else printf("Not Found\n");

6 Binary Tree Traversal Array Linked List Linear Data Structure
Tree traversal is the process of visiting each node in the tree exactly once in some order Visit Reading/Processing data in a node Head

7 Tree Traversal Breadth First Depth First Breadth-First: P, D, J, B, E, G, K, A, C, I, Y Depth-First: 3 Strategies Preorder (Root, Left-Subtree, Right-Subtree): P, D, B, A, C, E, J, G, I, Y, K Inorder (Left-subtree, Root, Right-subtree): A, B, C, D, E, P, G, Y, I, J, K Postorder (Left-subtree, Right-subtree, Root): A, C, B, E, D, Y, I, G, K, J, P


Download ppt "Tree data structure."

Similar presentations


Ads by Google