Instinctually, you might think that once we find a “1” we initiate a new component. This falls under a general category of problems where we have to find the number of connected components, but the details are a bit tweaked. Public class NumberOfConnectedComponents 200. The value of ans will be incremented by 1. We will start from a node, and while carrying out DFS on that node (of course, using our magic spell), it will mark all the nodes connected to it as visited. Our approach here is to create a variable called ans that stores the number of connected components.įirst, we will initialize all vertices as unvisited. Number of Connected Components in an Undirected Graph But here, we will visit everything on the left side of a node, print the node, and then visit everything on the right side of the node. Our approach to solve this problem is similar to the previous problems. Binary Tree Inorder Traversal (Difficulty: Medium) It takes constant time to add an element to the head of a linked list. But think about it – that would cost O(n) time complexity to reverse it.Ī smarter solution is to copy and paste the exact code of the pre-order traversal, but put the result at the top of the linked list (index 0) at each iteration. So one solution that might come to mind right now is simply reversing the resulting array of pre-order traversal. This means post order traversal is exactly the reverse of pre-order traversal. Pre-order traversal is root-left-right, and post-order is right-left-root. Binary Tree Postorder Traversal (Difficulty: Hard) The process is continued in a similar manner until the whole graph has been traversed and all the node values of the binary tree enter into the resulting list. The next element to be popped from the stack will be the top element of the stack right now: the left child of root node. Thus, the first element in the result list is the root (hence the name, Pre-order). While the stack is not empty, we pop it, and push its right and left child into the stack.Īs we pop the root node, we immediately put it into our result list. Let's understand the simulation really well since this is the basic template we will be using to solve the rest of the problems.Īt first, we push the root node into the stack. To solve this question all we need to do is simply recall our magic spell. Binary Tree Preorder Traversal (Difficulty: Medium)
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |