LEARNING JOURNAL

I created this learning journal to practice writting and to help me learn by writting everything down. Source code here

2/28/2024

Binary Tree Level Order Traversal

THE PROBLEM

My approach to this problem is using an array arr and a pointer p to mimic a queue. Then, I traverse the tree using breadth-first-search to add tree nodes to the queue and separate each level by null. There is another array named level to collect the values, then, when the pointer p reaches null, all content of level will be copied to the array result to return.

There is another approach that is faster, which uses 2 arrays, current and next to store the values of the current level and next level. You push the current to the array result while adding elements to the next array.

Revised by ChatGPT

My solution for this problem employs a breadth-first search approach using a simulated queue with an array queue and a pointer p. The algorithm traverses the tree level by level and uses null as a marker to separate each level.

  • An array level is used to collect the values of the current level.
  • When the pointer p encounters null, it indicates the end of a level. The contents of level are then copied to the result array, and level is reset for the next level.
  • If p is not at the end of the queue, a new null marker is added to indicate the end of the next level.

An alternative, more efficient approach uses two arrays, current and next, to store the values of the current and next levels, respectively. After processing all nodes in the current level, the contents are moved to the result array, and next becomes the new current level.