diff --git a/codeharborhub b/codeharborhub new file mode 160000 index 000000000..08e05f289 --- /dev/null +++ b/codeharborhub @@ -0,0 +1 @@ +Subproject commit 08e05f289d8a4b672c1e5cbd559142f9a217acb6 diff --git a/dsa/intermediate/Graph_traversal.md b/dsa/intermediate/Graph_traversal.md new file mode 100644 index 000000000..2aec3e86e --- /dev/null +++ b/dsa/intermediate/Graph_traversal.md @@ -0,0 +1,418 @@ +--- +id: 02-graph-traversal +title: Graph Data Structure Traversal Methods +sidebar_label: Graph Traversal methods +tags: + - dsa + - data-structures + - graph + - graph-traversal + - bfs + - dfs + - intermediate + - javascript + - python + - c++ + - java + - programming + - tutorial +sidebar_position: 5 +--- +## What is Graph Data Structure +Graph Data Structure is a collection of vertices connected by edges. The vertices(V) are also referred as nodes and lines connecting any two nodes are called edges(E). A graph is denoted by G(V,E). + +![Local Image](graph.png) +## Traversal Methods in Graph +Two very popular traversal methods in Graph are: +* BFS (Breadth First Search) +* DFS (Depth First Search) + +## BFS (Breadth First Search) +Breadth First Search traversal algorithm in graph is similar to level order traversal of tree. It starts at a specified vertex and visits all its neighbors before moving on to the next level of neighbors. BFS is commonly used in algorithms for pathfinding, connected components, and shortest path problems in graphs. +### Algorithm: +1. Use adjacency list or adjacency matrix to store the graph, queue and a visiting array to keep the track of the visited vertex. +2. Strat traversal from any vertex. +3. Drop that vertex into queue +4. Take out the vertex from queue and explore it. +5. While exploring, go to all the adjacent vertices and add them to queue. +6. Repeat step 4 and 5 unitl queue is not empty. + +### BFS Program + + + ```Cpp showLineNumbers + /*write a cpp program to implement bfs algorithm*/ +#include +#include +#include +using namespace std; +void bfs(int source, vector>&graph,int vertex) +{ + queuequ; + vectorvisited(vertex,0); + qu.push(source); + visited[source]=1; + cout<>adjlis(vertex); //using adjacent list method to represent graph + //there are 9 edges in the graph + adjlis[0].push_back(2); + adjlis[0].push_back(1); + adjlis[0].push_back(3); + adjlis[1].push_back(3); + adjlis[2].push_back(3); + adjlis[2].push_back(4); + adjlis[3].push_back(4); + adjlis[4].push_back(5); + adjlis[4].push_back(6); + + bfs(0,adjlis,vertex); + return 0; +} + ``` + + + + ```Python showLineNumbers + from collections import deque + def bfs(source, graph, vertex): + qu = deque() + visited = [0] * vertex + qu.append(source) + visited[source] = 1 + print(source, end=" ") + + while qu: + u = qu.popleft() + for it in graph[u]: + if visited[it] == 0: + print(it, end=" ") + visited[it] = 1 + qu.append(it) + + def main(): + vertex = 7 + adjlis = [[] for _ in range(vertex)] # using adjacency list method to represent graph + # there are 9 edges in the graph + adjlis[0].extend([2, 1, 3]) + adjlis[1].append(3) + adjlis[2].extend([3, 4]) + adjlis[3].append(4) + adjlis[4].extend([5, 6]) + + bfs(0, adjlis, vertex) + + if __name__ == "__main__": + main() + + ``` + + + +```jsx showLineNumbers +import java.util.*; + +public class Main { + public static void bfs(int source, List> graph, int vertex) { + Queue qu = new LinkedList<>(); + boolean[] visited = new boolean[vertex]; + qu.add(source); + visited[source] = true; + System.out.print(source + " "); + + while (!qu.isEmpty()) { + int u = qu.poll(); + for (int it : graph.get(u)) { + if (!visited[it]) { + System.out.print(it + " "); + visited[it] = true; + qu.add(it); + } + } + } + } + + public static void main(String[] args) { + int vertex = 7; + List> adjlis = new ArrayList<>(vertex); + + for (int i = 0; i < vertex; i++) { + adjlis.add(new ArrayList<>()); + } + + // There are 9 edges in the graph + adjlis.get(0).addAll(Arrays.asList(2, 1, 3)); + adjlis.get(1).add(3); + adjlis.get(2).addAll(Arrays.asList(3, 4)); + adjlis.get(3).add(4); + adjlis.get(4).addAll(Arrays.asList(5, 6)); + + bfs(0, adjlis, vertex); + } +} + +``` + + + +```JavaScript showLineNumbers +class Graph { + constructor(vertex) { + this.vertex = vertex; + this.adjList = new Array(vertex).fill(null).map(() => []); + } + + addEdge(src, dest) { + this.adjList[src].push(dest); + } + + bfs(source) { + const visited = new Array(this.vertex).fill(false); + const queue = []; + visited[source] = true; + queue.push(source); + + while (queue.length !== 0) { + const u = queue.shift(); + console.log(u); + + for (const it of this.adjList[u]) { + if (!visited[it]) { + visited[it] = true; + queue.push(it); + } + } + } + } +} + +const main = () => { + const vertex = 7; + const graph = new Graph(vertex); + + // There are 9 edges in the graph + graph.addEdge(0, 2); + graph.addEdge(0, 1); + graph.addEdge(0, 3); + graph.addEdge(1, 3); + graph.addEdge(2, 3); + graph.addEdge(2, 4); + graph.addEdge(3, 4); + graph.addEdge(4, 5); + graph.addEdge(4, 6); + + graph.bfs(0); +}; + +main(); +``` + + +Output:
+ +``` +0 2 1 3 4 5 6 +``` + +## DFS (Depth First Search) +Depth First Search traversal algorithm is similar to Pre-order traversal in binary tree. DFS use stack data structure here (or recursion as stack).he algorithm starts at the root node (selecting some arbitrary node as the root node in the case of a graph) and explores as far as possible along each branch before backtracking. + +### Algorithm: +1. Use adjacency list or adjacency matrix to store the graph, queue and a visiting array to keep the track of the visited vertex. +2. Start with any vertex and start exploring. +3. After getting first element suspend the previous one in the stack and now start exploring this vertex. +4. If cannot explore more go back to previous vertex (backtraking) from stack and explore that +5. Repeat 3 and 4 until stack is empty. + +### DFS Program + + + ```Cpp showLineNumbers + #include +#include +using namespace std; + +// Function for DFS traversal +void DFS(int u, vector>& G, vector& visited) { + cout << u << " "; + visited[u] = 1; + + for (int v = 0; v < G.size(); ++v) { + if (G[u][v] == 1 && visited[v] == 0) { + DFS(v, G, visited); + } + } +} + +int main() { + int vertex=7; + + //using adjacent matrix method to represent graph + vector> G{{0,1,1,1,0,0,0}, + {1,0,0,1,1,0,0}, + {1,0,0,1,0,0,0}, + {1,1,1,0,1,0,0}, + {0,1,0,1,0,1,1}, + {0,0,0,0,1,0,0}, + {0,0,0,0,1,0,0}}; + + + vector visited(vertex, 0); // Initialize visited array to 0 + + cout << "DFS traversal starting from vertex 0: "; + DFS(0, G, visited); + + return 0; +} + ``` + + + + ```Python showLineNumbers + def dfs(u, graph, visited): + print(u, end=" ") + visited[u] = 1 + + for v in range(len(graph)): + if graph[u][v] == 1 and not visited[v]: + dfs(v, graph, visited) + +def main(): + vertex = 7 + + graph = [ + [0, 1, 1, 1, 0, 0, 0], + [1, 0, 0, 1, 1, 0, 0], + [1, 0, 0, 1, 0, 0, 0], + [1, 1, 1, 0, 1, 0, 0], + [0, 1, 0, 1, 0, 1, 1], + [0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 1, 0, 0] + ] + + visited = [0] * vertex # Initialize visited array to 0 + + print("DFS traversal starting from vertex 0: ", end="") + dfs(0, graph, visited) + +if __name__ == "__main__": + main() + + ``` + + + + ```jsx showLineNumbers + import java.util.*; + +public class DFS { + // Function for DFS traversal + public static void dfs(int u, int[][] graph, boolean[] visited) { + System.out.print(u + " "); + visited[u] = true; + + for (int v = 0; v < graph.length; v++) { + if (graph[u][v] == 1 && !visited[v]) { + dfs(v, graph, visited); + } + } + } + + public static void main(String[] args) { + int vertex = 7; + + int[][] graph = { + {0, 1, 1, 1, 0, 0, 0}, + {1, 0, 0, 1, 1, 0, 0}, + {1, 0, 0, 1, 0, 0, 0}, + {1, 1, 1, 0, 1, 0, 0}, + {0, 1, 0, 1, 0, 1, 1}, + {0, 0, 0, 0, 1, 0, 0}, + {0, 0, 0, 0, 1, 0, 0} + }; + + boolean[] visited = new boolean[vertex]; // Initialize visited array to false + + System.out.print("DFS traversal starting from vertex 0: "); + dfs(0, graph, visited); + } +} + + ``` + + + + ```JavaScript showLineNumbers + class Graph { + constructor(vertex) { + this.vertex = vertex; + this.adjList = new Array(vertex).fill(null).map(() => []); + } + + addEdge(src, dest) { + this.adjList[src].push(dest); + } + + dfsUtil(v, visited) { + visited[v] = true; + console.log(v + " "); + + this.adjList[v].forEach(neighbour => { + if (!visited[neighbour]) { + this.dfsUtil(neighbour, visited); + } + }); + } + + dfs(v) { + let visited = new Array(this.vertex).fill(false); + this.dfsUtil(v, visited); + } +} + +const main = () => { + const vertex = 7; + const graph = new Graph(vertex); + + graph.addEdge(0, 1); + graph.addEdge(0, 2); + graph.addEdge(0, 3); + graph.addEdge(1, 3); + graph.addEdge(1, 4); + graph.addEdge(2, 3); + graph.addEdge(3, 4); + graph.addEdge(4, 5); + graph.addEdge(4, 6); + + console.log("DFS traversal starting from vertex 0: "); + graph.dfs(0); +}; + +main(); + + ``` + + +Output:
+ +``` +DFS traversal starting from vertex 0: 0 1 3 2 4 5 6 +``` diff --git a/dsa/intermediate/_category_.json b/dsa/intermediate/_category_.json index d5fa02b1a..26b212a40 100644 --- a/dsa/intermediate/_category_.json +++ b/dsa/intermediate/_category_.json @@ -1,8 +1,8 @@ -{ - "label": "Intermediate", - "position": 2, - "link": { - "type": "generated-index", - "description": "Learn the intermediate of the Data Structures." - } +{ + "label": "Intermediate", + "position": 2, + "link": { + "type": "generated-index", + "description": "Learn the intermediate of the Data Structures." + } } \ No newline at end of file diff --git a/dsa/intermediate/binary_tree.md b/dsa/intermediate/binary_tree.md index 8cb393668..a41c99645 100644 --- a/dsa/intermediate/binary_tree.md +++ b/dsa/intermediate/binary_tree.md @@ -1,597 +1,597 @@ ---- -id: 01-binary-tree -title: Introduction to Binary Tree -sidebar_label: Binary Tree -tags: - - dsa - - data-structures - - binary-tree - - intermediate - - javascript - - python - - c++ - - java - - programming - - tutorial -sidebar_position: 5 ---- -In this tutorial we will explore one of the fundamental data structure in computer science: Binary Tree -# What is a Binary Tree? -A binary tree is a hierarchical data structure composed of nodes, where each node has at most two children: a left child and a right child. The topmost node of the tree is called the root node. Each child node can have its own left and right children, forming sub-trees. - - - -## Representation of a Node Binary Tree -Binary Tree is made up of nodes, where each node except leaf nodes have children. Each node in the tree consist of three parts i.e., data, left pointer, right pointer. To create a node we can follow the below structure of code: - - - - ```Cpp showLineNumbers - //Creating a node in C++ using structure - - typedef struct treetype - { - struct treetype *left; - int data; - struct treetype *right; - }node; - - //Creating a node in C++ using class - class Node{ - public: - Node *left; - int data; - Node *right; - }; - ``` - - - - ```Python showLineNumbers - #Creating a node in Python - - class Node: - def __init__(self, val): - self.left = None - self.data = val - self.right = None - ``` - - - - ```jsx showLineNumbers - //Creating a node in Java - - class Node{ - int data; - Node left,right; - public Node(int val) - { - left=null; - data=val; - right=null; - } - } - ``` - - - - ```JavaScript showLineNumbers - //Creating a node in JavaScript - - class Node - { - constructor(val) - { - this.left=null; - this.data=val; - this.right=null; - } - } - ``` - - - -## Operation in Binary Tree -### 1. Insert Operation: -We can add a node in the Binary Tree as a left child or right child of any node. -
-**Algorithm or steps to insert in a binary tree**
-* First check if the root is null or not if root is null means this is the first node of the tree, make it as a root and return it else move to next step -* Now as we have already studient queue data strucuture, we will use that to add nodes to the binary tree -* Insert a node as the left or right child of the parent node if the parent node points to null -* Return root to main function. - -### 2. Traversal of Binary Tree: -Traversal means visiting all nodes of the binary tree. Three famous binary tree traversal methods are:
-* **Preorder Traversal (NLR) :** In this traversal method we have to visit the current node before visiting its left or right subtree. The traversal is Node-left-right means first node (root node) is traveresed then left child and then right child -* **Inorder Traversal (LNR) :** In this traversal method we have to visit all the nodes inside the left subtree first then visit the current node and then the nodes in the right subtree. The traversal is Left-Node-right. -* **Postorder Traversal (LRN) :** In this traversal method we visit the current node after visiting all the nodes in left and right subtree. The traversal is in the order left-right-node. - -### 3. Search in Binary Tree: -We can search any element in the Binary Tree using the same algorithm as insertion just with some difference
-**Algorithm or steps to insert in a binary tree**
-*First check if the root is null or not if root is null return false to main else move to next step.
-*Store the root in a queue, start a loop which ends when queue is empty.
-*Take the front node (as temp) from queue check the temp value with the search value given if same return true to main else move to next step.
-*Check if the temp left or temp right child are NULL or not , if null continue the loop, else push the left then right child in the queue.
-*If the queue comes empty and element is not found return false to main.
- -## Programming implementation of operation in Binary Tree - - - ```Cpp showLineNumbers - #include - #include - using namespace std; - class Node - { - public: - Node *left,*right; - int data; - Node(int val) - { - left=NULL; - data=val; - right=NULL; - } - }; - //insert function for binary search - Node* insert(Node* root, int data) - { - if (root==NULL){ - root=new Node(data); - return root; - } - //using queue data structure to find the position to insert the node - queuestore; - store.push(root); - while(!store.empty()) - { - Node *temp=store.front(); - store.pop(); - //check for left and right child - if (temp->left==NULL) - { - temp->left=new Node(data); - break; - } - else - store.push(temp->left); - if (temp->right==NULL) - { - temp->right=new Node(data); - break; - } - else - store.push(temp->right); - } - return root; - } - //now traversals methods of binary tree - //PRE-ORDER traversal - void pre_traversal(Node* root) - { - if (root==NULL) - return; - cout<data<<" "; - pre_traversal(root->left); - pre_traversal(root->right); - } - //IN-ORDER traversal - void in_traversal(Node *root) - { - if(root==NULL) - return ; - in_traversal(root->left); - cout<data<<" "; - in_traversal(root->right); - } - //POST-ORDER traversal - void post_traversal(Node *root) - { - if (root==NULL) - return ; - post_traversal(root->left); - post_traversal(root->right); - cout<data<<" "; - } - //search function for binary tree - bool search(Node *root, int value) - { - if (root==NULL) - return false; - queuestore; - store.push(root); - while(!store.empty()) - { - Node *temp=store.front(); - store.pop(); - if (temp->data==value) - return true; - if (temp->left!=NULL) - { - store.push(temp->left); - } - if (temp->right!=NULL) - { - store.push(temp->right); - } - } - return false; - } - int main() - { - Node *root=NULL; - //insertion operation in binary tree - root=insert(root,1); - root=insert(root,2); - root=insert(root,3); - root=insert(root,4); - root=insert(root,5); - //traversal - //preorder traversal - cout<<"Preorder Traversal: "; - pre_traversal(root); - //inorder traversal - cout< - - - ```Python showLineNumbers - from collections import deque - - class Node: - def __init__(self, val): - self.left = None - self.data = val - self.right = None - - # Insert function for binary search - def insert(root, data): - if root is None: - root = Node(data) - return root - # Using queue data structure to find the position to insert the node - store = deque([root]) - while store: - temp = store.popleft() - # Check for left and right child - if temp.left is None: - temp.left = Node(data) - break - else: - store.append(temp.left) - if temp.right is None: - temp.right = Node(data) - break - else: - store.append(temp.right) - return root - - # Now traversal methods of binary tree - # PRE-ORDER traversal - def pre_traversal(root): - if root is None: - return - print(root.data, end=" ") - pre_traversal(root.left) - pre_traversal(root.right) - - # IN-ORDER traversal - def in_traversal(root): - if root is None: - return - in_traversal(root.left) - print(root.data, end=" ") - in_traversal(root.right) - - # POST-ORDER traversal - def post_traversal(root): - if root is None: - return - post_traversal(root.left) - post_traversal(root.right) - print(root.data, end=" ") - - # Search function for binary tree - def search(root, value): - if root is None: - return False - store = deque([root]) - while store: - temp = store.popleft() - if temp.data == value: - return True - if temp.left is not None: - store.append(temp.left) - if temp.right is not None: - store.append(temp.right) - return False - - # Main function - def main(): - root = None - # Insertion operation in binary tree - root = insert(root, 1) - root = insert(root, 2) - root = insert(root, 3) - root = insert(root, 4) - root = insert(root, 5) - - # Traversal - # Preorder traversal - print("Preorder Traversal:", end=" ") - pre_traversal(root) - # Inorder traversal - print("\nInorder Traversal:", end=" ") - in_traversal(root) - # Postorder traversal - print("\nPost-order Traversal:", end=" ") - post_traversal(root) - - # Searching a node in the binary tree - if search(root, 4): - print("\nNode found in the binary tree") - else: - print("\nNode not found in the binary tree") - - if __name__ == "__main__": - main() - - ``` - - - - ```jsx showLineNumbers - import java.util.LinkedList; - import java.util.Queue; - - class Node { - Node left, right; - int data; - - Node(int val) { - left = null; - data = val; - right = null; - } - } - - public class BinaryTree { - // Insert function for binary search - static Node insert(Node root, int data) { - if (root == null) { - root = new Node(data); - return root; - } - // Using queue data structure to find the position to insert the node - Queue store = new LinkedList<>(); - store.add(root); - while (!store.isEmpty()) { - Node temp = store.poll(); - // Check for left and right child - if (temp.left == null) { - temp.left = new Node(data); - break; - } else - store.add(temp.left); - if (temp.right == null) { - temp.right = new Node(data); - break; - } else - store.add(temp.right); - } - return root; - } - - // Now traversal methods of binary tree - // PRE-ORDER traversal - static void preTraversal(Node root) { - if (root == null) - return; - System.out.print(root.data + " "); - preTraversal(root.left); - preTraversal(root.right); - } - - // IN-ORDER traversal - static void inTraversal(Node root) { - if (root == null) - return; - inTraversal(root.left); - System.out.print(root.data + " "); - inTraversal(root.right); - } - - // POST-ORDER traversal - static void postTraversal(Node root) { - if (root == null) - return; - postTraversal(root.left); - postTraversal(root.right); - System.out.print(root.data + " "); - } - - // Search function for binary tree - static boolean search(Node root, int value) { - if (root == null) - return false; - Queue store = new LinkedList<>(); - store.add(root); - while (!store.isEmpty()) { - Node temp = store.poll(); - if (temp.data == value) - return true; - if (temp.left != null) - store.add(temp.left); - if (temp.right != null) - store.add(temp.right); - } - return false; - } - - public static void main(String[] args) { - Node root = null; - // Insertion operation in binary tree - root = insert(root, 1); - root = insert(root, 2); - root = insert(root, 3); - root = insert(root, 4); - root = insert(root, 5); - - // Traversal - // Preorder traversal - System.out.print("Preorder Traversal: "); - preTraversal(root); - // Inorder traversal - System.out.print("\nInorder Traversal: "); - inTraversal(root); - // Postorder traversal - System.out.print("\nPost-order Traversal: "); - postTraversal(root); - - // Searching a node in the binary tree - if (search(root, 4)) - System.out.println("\nNode found in the binary tree"); - else - System.out.println("\nNode not found in the binary tree"); - } - } - - ``` - - - - ```javaScript showLineNumbers - class Node { - constructor(val) { - this.left = null; - this.data = val; - this.right = null; - } - } - - // Insert function for binary search - function insert(root, data) { - if (root === null) { - root = new Node(data); - return root; - } - // Using queue data structure to find the position to insert the node - let store = [root]; - while (store.length > 0) { - let temp = store.shift(); - // Check for left and right child - if (temp.left === null) { - temp.left = new Node(data); - break; - } else - store.push(temp.left); - if (temp.right === null) { - temp.right = new Node(data); - break; - } else - store.push(temp.right); - } - return root; - } - - // Now traversal methods of binary tree - // PRE-ORDER traversal - function preTraversal(root) { - if (root === null) - return; - process.stdout.write(root.data + " "); - preTraversal(root.left); - preTraversal(root.right); - } - - // IN-ORDER traversal - function inTraversal(root) { - if (root === null) - return; - inTraversal(root.left); - process.stdout.write(root.data + " "); - inTraversal(root.right); - } - - // POST-ORDER traversal - function postTraversal(root) { - if (root === null) - return; - postTraversal(root.left); - postTraversal(root.right); - process.stdout.write(root.data + " "); - } - - // Search function for binary tree - function search(root, value) { - if (root === null) - return false; - let store = [root]; - while (store.length > 0) { - let temp = store.shift(); - if (temp.data === value) - return true; - if (temp.left !== null) - store.push(temp.left); - if (temp.right !== null) - store.push(temp.right); - } - return false; - } - - // Main function - function main() { - let root = null; - // Insertion operation in binary tree - root = insert(root, 1); - root = insert(root, 2); - root = insert(root, 3); - root = insert(root, 4); - root = insert(root, 5); - - // Traversal - // Preorder traversal - process.stdout.write("Preorder Traversal: "); - preTraversal(root); - // Inorder traversal - process.stdout.write("\nInorder Traversal: "); - inTraversal(root); - // Postorder traversal - process.stdout.write("\nPost-order Traversal: "); - postTraversal(root); - - // Searching a node in the binary tree - if (search(root, 4)) - console.log("\nNode found in the binary tree"); - else - console.log("\nNode not found in the binary tree"); - } - - main(); - ``` - - - -Output:
- -``` -Preorder Traversal: 1 2 4 5 3 -Inorder Traversal: 4 2 5 1 3 -Post-order Traversal: 4 5 2 3 1 -Node found in the binary tree -``` +--- +id: 01-binary-tree +title: Introduction to Binary Tree +sidebar_label: Binary Tree +tags: + - dsa + - data-structures + - binary-tree + - intermediate + - javascript + - python + - c++ + - java + - programming + - tutorial +sidebar_position: 5 +--- +In this tutorial we will explore one of the fundamental data structure in computer science: Binary Tree +# What is a Binary Tree? +A binary tree is a hierarchical data structure composed of nodes, where each node has at most two children: a left child and a right child. The topmost node of the tree is called the root node. Each child node can have its own left and right children, forming sub-trees. + + + +## Representation of a Node Binary Tree +Binary Tree is made up of nodes, where each node except leaf nodes have children. Each node in the tree consist of three parts i.e., data, left pointer, right pointer. To create a node we can follow the below structure of code: + + + + ```Cpp showLineNumbers + //Creating a node in C++ using structure + + typedef struct treetype + { + struct treetype *left; + int data; + struct treetype *right; + }node; + + //Creating a node in C++ using class + class Node{ + public: + Node *left; + int data; + Node *right; + }; + ``` + + + + ```Python showLineNumbers + #Creating a node in Python + + class Node: + def __init__(self, val): + self.left = None + self.data = val + self.right = None + ``` + + + + ```jsx showLineNumbers + //Creating a node in Java + + class Node{ + int data; + Node left,right; + public Node(int val) + { + left=null; + data=val; + right=null; + } + } + ``` + + + + ```JavaScript showLineNumbers + //Creating a node in JavaScript + + class Node + { + constructor(val) + { + this.left=null; + this.data=val; + this.right=null; + } + } + ``` + + + +## Operation in Binary Tree +### 1. Insert Operation: +We can add a node in the Binary Tree as a left child or right child of any node. +
+**Algorithm or steps to insert in a binary tree**
+* First check if the root is null or not if root is null means this is the first node of the tree, make it as a root and return it else move to next step +* Now as we have already studient queue data strucuture, we will use that to add nodes to the binary tree +* Insert a node as the left or right child of the parent node if the parent node points to null +* Return root to main function. + +### 2. Traversal of Binary Tree: +Traversal means visiting all nodes of the binary tree. Three famous binary tree traversal methods are:
+* **Preorder Traversal (NLR) :** In this traversal method we have to visit the current node before visiting its left or right subtree. The traversal is Node-left-right means first node (root node) is traveresed then left child and then right child +* **Inorder Traversal (LNR) :** In this traversal method we have to visit all the nodes inside the left subtree first then visit the current node and then the nodes in the right subtree. The traversal is Left-Node-right. +* **Postorder Traversal (LRN) :** In this traversal method we visit the current node after visiting all the nodes in left and right subtree. The traversal is in the order left-right-node. + +### 3. Search in Binary Tree: +We can search any element in the Binary Tree using the same algorithm as insertion just with some difference
+**Algorithm or steps to insert in a binary tree**
+*First check if the root is null or not if root is null return false to main else move to next step.
+*Store the root in a queue, start a loop which ends when queue is empty.
+*Take the front node (as temp) from queue check the temp value with the search value given if same return true to main else move to next step.
+*Check if the temp left or temp right child are NULL or not , if null continue the loop, else push the left then right child in the queue.
+*If the queue comes empty and element is not found return false to main.
+ +## Programming implementation of operation in Binary Tree + + + ```Cpp showLineNumbers + #include + #include + using namespace std; + class Node + { + public: + Node *left,*right; + int data; + Node(int val) + { + left=NULL; + data=val; + right=NULL; + } + }; + //insert function for binary search + Node* insert(Node* root, int data) + { + if (root==NULL){ + root=new Node(data); + return root; + } + //using queue data structure to find the position to insert the node + queuestore; + store.push(root); + while(!store.empty()) + { + Node *temp=store.front(); + store.pop(); + //check for left and right child + if (temp->left==NULL) + { + temp->left=new Node(data); + break; + } + else + store.push(temp->left); + if (temp->right==NULL) + { + temp->right=new Node(data); + break; + } + else + store.push(temp->right); + } + return root; + } + //now traversals methods of binary tree + //PRE-ORDER traversal + void pre_traversal(Node* root) + { + if (root==NULL) + return; + cout<data<<" "; + pre_traversal(root->left); + pre_traversal(root->right); + } + //IN-ORDER traversal + void in_traversal(Node *root) + { + if(root==NULL) + return ; + in_traversal(root->left); + cout<data<<" "; + in_traversal(root->right); + } + //POST-ORDER traversal + void post_traversal(Node *root) + { + if (root==NULL) + return ; + post_traversal(root->left); + post_traversal(root->right); + cout<data<<" "; + } + //search function for binary tree + bool search(Node *root, int value) + { + if (root==NULL) + return false; + queuestore; + store.push(root); + while(!store.empty()) + { + Node *temp=store.front(); + store.pop(); + if (temp->data==value) + return true; + if (temp->left!=NULL) + { + store.push(temp->left); + } + if (temp->right!=NULL) + { + store.push(temp->right); + } + } + return false; + } + int main() + { + Node *root=NULL; + //insertion operation in binary tree + root=insert(root,1); + root=insert(root,2); + root=insert(root,3); + root=insert(root,4); + root=insert(root,5); + //traversal + //preorder traversal + cout<<"Preorder Traversal: "; + pre_traversal(root); + //inorder traversal + cout< + + + ```Python showLineNumbers + from collections import deque + + class Node: + def __init__(self, val): + self.left = None + self.data = val + self.right = None + + # Insert function for binary search + def insert(root, data): + if root is None: + root = Node(data) + return root + # Using queue data structure to find the position to insert the node + store = deque([root]) + while store: + temp = store.popleft() + # Check for left and right child + if temp.left is None: + temp.left = Node(data) + break + else: + store.append(temp.left) + if temp.right is None: + temp.right = Node(data) + break + else: + store.append(temp.right) + return root + + # Now traversal methods of binary tree + # PRE-ORDER traversal + def pre_traversal(root): + if root is None: + return + print(root.data, end=" ") + pre_traversal(root.left) + pre_traversal(root.right) + + # IN-ORDER traversal + def in_traversal(root): + if root is None: + return + in_traversal(root.left) + print(root.data, end=" ") + in_traversal(root.right) + + # POST-ORDER traversal + def post_traversal(root): + if root is None: + return + post_traversal(root.left) + post_traversal(root.right) + print(root.data, end=" ") + + # Search function for binary tree + def search(root, value): + if root is None: + return False + store = deque([root]) + while store: + temp = store.popleft() + if temp.data == value: + return True + if temp.left is not None: + store.append(temp.left) + if temp.right is not None: + store.append(temp.right) + return False + + # Main function + def main(): + root = None + # Insertion operation in binary tree + root = insert(root, 1) + root = insert(root, 2) + root = insert(root, 3) + root = insert(root, 4) + root = insert(root, 5) + + # Traversal + # Preorder traversal + print("Preorder Traversal:", end=" ") + pre_traversal(root) + # Inorder traversal + print("\nInorder Traversal:", end=" ") + in_traversal(root) + # Postorder traversal + print("\nPost-order Traversal:", end=" ") + post_traversal(root) + + # Searching a node in the binary tree + if search(root, 4): + print("\nNode found in the binary tree") + else: + print("\nNode not found in the binary tree") + + if __name__ == "__main__": + main() + + ``` + + + + ```jsx showLineNumbers + import java.util.LinkedList; + import java.util.Queue; + + class Node { + Node left, right; + int data; + + Node(int val) { + left = null; + data = val; + right = null; + } + } + + public class BinaryTree { + // Insert function for binary search + static Node insert(Node root, int data) { + if (root == null) { + root = new Node(data); + return root; + } + // Using queue data structure to find the position to insert the node + Queue store = new LinkedList<>(); + store.add(root); + while (!store.isEmpty()) { + Node temp = store.poll(); + // Check for left and right child + if (temp.left == null) { + temp.left = new Node(data); + break; + } else + store.add(temp.left); + if (temp.right == null) { + temp.right = new Node(data); + break; + } else + store.add(temp.right); + } + return root; + } + + // Now traversal methods of binary tree + // PRE-ORDER traversal + static void preTraversal(Node root) { + if (root == null) + return; + System.out.print(root.data + " "); + preTraversal(root.left); + preTraversal(root.right); + } + + // IN-ORDER traversal + static void inTraversal(Node root) { + if (root == null) + return; + inTraversal(root.left); + System.out.print(root.data + " "); + inTraversal(root.right); + } + + // POST-ORDER traversal + static void postTraversal(Node root) { + if (root == null) + return; + postTraversal(root.left); + postTraversal(root.right); + System.out.print(root.data + " "); + } + + // Search function for binary tree + static boolean search(Node root, int value) { + if (root == null) + return false; + Queue store = new LinkedList<>(); + store.add(root); + while (!store.isEmpty()) { + Node temp = store.poll(); + if (temp.data == value) + return true; + if (temp.left != null) + store.add(temp.left); + if (temp.right != null) + store.add(temp.right); + } + return false; + } + + public static void main(String[] args) { + Node root = null; + // Insertion operation in binary tree + root = insert(root, 1); + root = insert(root, 2); + root = insert(root, 3); + root = insert(root, 4); + root = insert(root, 5); + + // Traversal + // Preorder traversal + System.out.print("Preorder Traversal: "); + preTraversal(root); + // Inorder traversal + System.out.print("\nInorder Traversal: "); + inTraversal(root); + // Postorder traversal + System.out.print("\nPost-order Traversal: "); + postTraversal(root); + + // Searching a node in the binary tree + if (search(root, 4)) + System.out.println("\nNode found in the binary tree"); + else + System.out.println("\nNode not found in the binary tree"); + } + } + + ``` + + + + ```javaScript showLineNumbers + class Node { + constructor(val) { + this.left = null; + this.data = val; + this.right = null; + } + } + + // Insert function for binary search + function insert(root, data) { + if (root === null) { + root = new Node(data); + return root; + } + // Using queue data structure to find the position to insert the node + let store = [root]; + while (store.length > 0) { + let temp = store.shift(); + // Check for left and right child + if (temp.left === null) { + temp.left = new Node(data); + break; + } else + store.push(temp.left); + if (temp.right === null) { + temp.right = new Node(data); + break; + } else + store.push(temp.right); + } + return root; + } + + // Now traversal methods of binary tree + // PRE-ORDER traversal + function preTraversal(root) { + if (root === null) + return; + process.stdout.write(root.data + " "); + preTraversal(root.left); + preTraversal(root.right); + } + + // IN-ORDER traversal + function inTraversal(root) { + if (root === null) + return; + inTraversal(root.left); + process.stdout.write(root.data + " "); + inTraversal(root.right); + } + + // POST-ORDER traversal + function postTraversal(root) { + if (root === null) + return; + postTraversal(root.left); + postTraversal(root.right); + process.stdout.write(root.data + " "); + } + + // Search function for binary tree + function search(root, value) { + if (root === null) + return false; + let store = [root]; + while (store.length > 0) { + let temp = store.shift(); + if (temp.data === value) + return true; + if (temp.left !== null) + store.push(temp.left); + if (temp.right !== null) + store.push(temp.right); + } + return false; + } + + // Main function + function main() { + let root = null; + // Insertion operation in binary tree + root = insert(root, 1); + root = insert(root, 2); + root = insert(root, 3); + root = insert(root, 4); + root = insert(root, 5); + + // Traversal + // Preorder traversal + process.stdout.write("Preorder Traversal: "); + preTraversal(root); + // Inorder traversal + process.stdout.write("\nInorder Traversal: "); + inTraversal(root); + // Postorder traversal + process.stdout.write("\nPost-order Traversal: "); + postTraversal(root); + + // Searching a node in the binary tree + if (search(root, 4)) + console.log("\nNode found in the binary tree"); + else + console.log("\nNode not found in the binary tree"); + } + + main(); + ``` + + + +Output:
+ +``` +Preorder Traversal: 1 2 4 5 3 +Inorder Traversal: 4 2 5 1 3 +Post-order Traversal: 4 5 2 3 1 +Node found in the binary tree +``` diff --git a/dsa/intermediate/graph.png b/dsa/intermediate/graph.png new file mode 100644 index 000000000..43d78b555 Binary files /dev/null and b/dsa/intermediate/graph.png differ