You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/main/java/g0101_0200/s0102_binary_tree_level_order_traversal/readme.md
+26-27
Original file line number
Diff line number
Diff line change
@@ -29,61 +29,60 @@ Given the `root` of a binary tree, return _the level order traversal of its node
29
29
* The number of nodes in the tree is in the range `[0, 2000]`.
30
30
*`-1000 <= Node.val <= 1000`
31
31
32
-
To solve this problem in Java with a `Solution` class, we'll use a breadth-first search (BFS) traversal approach. Below are the steps:
32
+
To solve the "Binary Tree Level Order Traversal" problem in Java with a `Solution` class, we'll perform a breadth-first search (BFS) traversal of the binary tree. Below are the steps:
33
33
34
34
1.**Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.
35
35
36
36
2.**Create a `levelOrder` method**: This method takes the root node of the binary tree as input and returns the level order traversal of its nodes' values.
37
37
38
-
3.**Check for null root**: Check if the root is null. If so, return an empty list since there are no nodes to traverse.
38
+
3.**Initialize a queue**: Create a queue to store the nodes during BFS traversal.
39
39
40
-
4.**Initialize a queue**: We'll use a queue to perform BFS traversal. Add the root node to the queue.
40
+
4.**Check for null root**: Check if the root is null. If it is, return an empty list.
41
41
42
-
5.**Traverse the tree level by level**:
43
-
- Start a loop that continues until the queue is empty.
44
-
- Inside the loop, for each level, get the size of the queue (number of nodes at the current level).
45
-
- Create a list to store the node values at the current level.
46
-
- Iterate through all nodes at the current level:
47
-
- Poll a node from the queue.
48
-
- Add its value to the list.
49
-
- If the node has left or right children, add them to the queue.
50
-
- After processing all nodes at the current level, add the list of node values to the result list.
42
+
5.**Perform BFS traversal**: Enqueue the root node into the queue. While the queue is not empty:
43
+
- Dequeue the front node from the queue.
44
+
- Add the value of the dequeued node to the current level list.
45
+
- Enqueue the left and right children of the dequeued node if they exist.
46
+
- Move to the next level when all nodes in the current level are processed.
51
47
52
-
6.**Return the result**: After traversing the entire tree, return the result containing the level order traversal.
48
+
6.**Return the result**: After the BFS traversal is complete, return the list containing the level order traversal of the binary tree.
0 commit comments