What are trees in Data Structure?
Trees are non-linear DS
Where are Trees used?
Anywhere hierarchy is present. Like File and Folder structures.
What does Binary means in Binary Tree.
Why BT is Important?
What is Root in BT? What are childrens? What are Leaf Nodes? What is subtree?
What is Ancestors?
Types of Binary Tree
what is full binary tree
Either has 0 or 2 childrens
what is complete binary tree
perfect BT
balanced BT
degenerate tree
How to represent BST in C
struct node{
int data;
struct node *left_child;
struct *right_child;
};
//function to create a node
struct node* new_node(int x) {
struct node *temp;
temp = malloc(sizeof(struct node));
temp -> data = x;
temp -> left_child = NULL;
temp -> right_child = NULL;
return temp;
}
// searching operation
struct node* search(struct node * root, int x) {
if (root == NULL || root -> data == x) //if root->data is x then the element is found
return root;
else if (x > root -> data) // x is greater, so we will search the right subtree
return search(root -> right_child, x);
else //x is smaller than the data, so we will search the left subtree
return search(root -> left_child, x);
}
// insertion
struct node* insert(struct node * root, int x) {
//searching for the place to insert
if (root == NULL)
return new_node(x);
else if (x > root -> data) // x is greater. Should be inserted to the right
root -> right_child = insert(root -> right_child, x);
else // x is smaller and should be inserted to left
root -> left_child = insert(root -> left_child, x);
return root;
}
Why traversal is required?
What are Types of traversal in Tree
DFS is further categorized into three more categories
- in order
- pre order
- post order
What is in-order traversal
What is Pre-order
Root => Left => Right
What is Post Order traversal
Left => Right => Root
What is BFS Traversal
Breath First Traversal
- write nodes level by level
- from left to right
Implementation of Pre-order
Algorithm / Steps
// Here we print the preorder recursively
// 1. we start from root of the tree
// 2.
void preorder (struct node *root)
{
if (root != NULL)
{
printf (“%d “, root->data);
preorder (root->left);
preorder (root->right);
}
}
In order Traversal Code
void inorder(node){
if node == null
return;
inorder(node->left)
print(node)
inorder(node->right)
}
Post order traversal code
// this node we passed here, is root node
void postorder(node)
{
if node == null
return;
postorder(node->left)
postorder(node->right)
print(node)
// L Ri Root
}
Level Order Traversal of Binary Tree / BFS.
What DS we need?
Write code for it
C++ code
// code for level order traversal
class solution{
public:
vector<vector<int>> levelOrder(TreeNode *root) {
if(root == NULL) return ans;</int>
queue<TreeNode*> q;
q.push(root);
while(!q.empty()) {
int size = q.size();
vector<int> level;</int>
for(int i=0; i < size ; i++) {
}
}
}
}