This idea is to use level order traversal to find all nodes at distance k from the root. Start by adding the root node to a queue and initialize the level to 0. While queue is not empty , process all nodes at the current level by dequeuing them, and enqueue their children. Once we have processed all nodes at a given level, we increment the level. If you reach level k, return the values of the nodes at that level. If the queue becomes empty before reaching k, return an empty list, indicating no nodes exist at that distance. Please refer to Print nodes at k distance from root | Iterative for implementation.
The idea is to use stack data structure to find all nodes at distance k from the root. Start by pushing the root node along with its level (0) onto the stack. While the stack has elements, we pop the top node and process it. If the node’s level matches k, we add its value to the result list. Otherwise, push its right child (with the incremented level) first, followed by the left child. This ensures the left child is processed first. Finally, return the result list with nodes at distance k. Please refer to Print nodes at k distance from root | Iterative for implementation.
Unlock your potential with our DSA Self-Paced course, designed to help you master Data Structures and Algorithms at your own pace. In 90 days, you’ll learn the core concepts of DSA, tackle real-world problems, and boost your problem-solving skills, all at a speed that fits your schedule. With comprehensive lessons and practical exercises, this course will set you up for success in technical interviews and beyond.
And here's the challenge – join the Three 90 Challenge! Complete 90% of the course in 90 days, and you’ll earn a 90% refund. It's a great way to stay motivated, track your progress, and reward yourself for your dedication. Start the challenge today, and push your limits to achieve mastery in DSA!