Добавить
Уведомления

BFS 1 - Easy - Binary Search Level Order Traversal - Java

Coding Interviews - Binary Search Level Order Traversal (LeetCode) This interview question is commonly asked by companies like Facebook, Amazon, Microsoft. We can use a Queue to efficiently traverse in BFS fashion. Here are the steps of our algorithm: -Start by pushing the root node to the queue. -Keep iterating until the queue is empty. -In each iteration, first count the elements in the queue (let’s call it levelSize). We will have these many nodes in the current level. -Next, remove levelSize nodes from the queue and push their value in an array to represent the current level. -After removing each node from the queue, insert both of its children into the queue. -If the queue is not empty, repeat from step 3 for the next level. Time Complexity - The time complexity of the above algorithm is O(N), where ‘N’ is the total number of nodes in the tree. This is due to the fact that we traverse each node once. Space Complexity - The space complexity of the above algorithm will be O(N) as we need to return a list containing the level order traversal. We will also need O(N) space for the queue. Know more about me LinkedIn - https://www.linkedin.com/in/umang-mavani/

12+
16 просмотров
2 года назад
12+
16 просмотров
2 года назад

Coding Interviews - Binary Search Level Order Traversal (LeetCode) This interview question is commonly asked by companies like Facebook, Amazon, Microsoft. We can use a Queue to efficiently traverse in BFS fashion. Here are the steps of our algorithm: -Start by pushing the root node to the queue. -Keep iterating until the queue is empty. -In each iteration, first count the elements in the queue (let’s call it levelSize). We will have these many nodes in the current level. -Next, remove levelSize nodes from the queue and push their value in an array to represent the current level. -After removing each node from the queue, insert both of its children into the queue. -If the queue is not empty, repeat from step 3 for the next level. Time Complexity - The time complexity of the above algorithm is O(N), where ‘N’ is the total number of nodes in the tree. This is due to the fact that we traverse each node once. Space Complexity - The space complexity of the above algorithm will be O(N) as we need to return a list containing the level order traversal. We will also need O(N) space for the queue. Know more about me LinkedIn - https://www.linkedin.com/in/umang-mavani/

, чтобы оставлять комментарии