Solution Review: Problem Challenge 1
We'll cover the following
Connect All Level Order Siblings (medium) #
Given a binary tree, connect each node with its level order successor. The last node of each level should point to the first node of the next level.
Solution #
This problem follows the Binary Tree Level Order Traversal pattern. We can follow the same BFS approach. The only difference will be that while traversing we will remember (irrespective of the level) the previous node to connect it with the current node.
Code #
Here is what our algorithm will look like; only the highlighted lines have changed:
Time complexity #
The time complexity of the above algorithm is , 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 which is required for the queue. Since we can have a maximum of nodes at any level (this could happen only at the lowest level), therefore we will need space to store them in the queue.