Level Order Successor (easy)
We'll cover the following
Problem Statement #
Given a binary tree and a node, find the level order successor of the given node in the tree. The level order successor is the node that appears right after the given node in the level order traversal.
Example 1:
Example 2:
Example 3:
Try it yourself #
Try solving this question here:
Solution #
This problem follows the Binary Tree Level Order Traversal pattern. We can follow the same BFS approach. The only difference will be that we will not keep track of all the levels. Instead we will keep inserting child nodes to the queue. As soon as we find the given node, we will return the next node from the queue as the level order successor.
Code #
Here is what our algorithm will look like; most of the changes are in the highlighted lines:
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.