Tree Level-Order Traversal
Given an array representing a complete binary tree in level-order, return the values in level-order traversal order — which is simply the array itself. Level-order traversal visits nodes from top to bottom, left to right, exactly as they appear in the array representation.
For example, the tree stored as [1, 2, 3, 4, 5] has level-order output [1, 2, 3, 4, 5]. The array is already in level-order, so the output is the same as the input. An empty tree returns [].
Level-order traversal (also called breadth-first traversal) visits all nodes at the current depth before moving to the next depth level. This is implemented using a queue: start by enqueueing the root, then repeatedly dequeue a node, process it, and enqueue its children (left then right).
For the array-based complete binary tree representation, the level-order traversal is the array itself because the array is already populated in level-order. However, for a tree represented as nodes with pointers, you would need the queue-based algorithm to produce the level-order sequence.
Edge cases include an empty tree (return []), a single-node tree (return [root]), and a tree where some nodes have only one child (the array still represents the complete tree structure).
Example Input & Output
Four nodes
Level order
Empty
Single
Full tree
Algorithm Flow
Solution Approach
Return the input array as-is, since it is already in level-order.
The array representation of a complete binary tree stores elements in level-order: the root at index 0, its children at 1 and 2, their children at 3-6, and so on. Therefore, the level-order traversal output is simply the array itself.
For a tree built from nodes with pointers, you would use a queue: initialize with the root, then while the queue is not empty, dequeue, add to result, and enqueue left then right children. This produces the same order as the array representation.
Time complexity is O(n), space complexity is O(n) for the result.
Best Answers
class Solution {
public int[] solution(int[] nums) {
return java.util.Arrays.copyOf(nums,nums.length);
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
