Skip to content

Commit 32d920f

Browse files
committed
Improved task 102
1 parent 9e98f74 commit 32d920f

File tree

1 file changed

+50
-17
lines changed
  • src/main/swift/g0101_0200/s0102_binary_tree_level_order_traversal

1 file changed

+50
-17
lines changed

src/main/swift/g0101_0200/s0102_binary_tree_level_order_traversal/readme.md

+50-17
Original file line numberDiff line numberDiff line change
@@ -32,20 +32,53 @@ Given the `root` of a binary tree, return _the level order traversal of its node
3232
* The number of nodes in the tree is in the range `[0, 2000]`.
3333
* `-1000 <= Node.val <= 1000`
3434

35-
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:
36-
37-
1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.
38-
39-
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.
40-
41-
3. **Initialize a queue**: Create a queue to store the nodes during BFS traversal.
42-
43-
4. **Check for null root**: Check if the root is null. If it is, return an empty list.
44-
45-
5. **Perform BFS traversal**: Enqueue the root node into the queue. While the queue is not empty:
46-
- Dequeue the front node from the queue.
47-
- Add the value of the dequeued node to the current level list.
48-
- Enqueue the left and right children of the dequeued node if they exist.
49-
- Move to the next level when all nodes in the current level are processed.
50-
51-
6. **Return the result**: After the BFS traversal is complete, return the list containing the level order traversal of the binary tree.
35+
## Solution
36+
37+
```swift
38+
/**
39+
* Definition for a binary tree node.
40+
* public class TreeNode {
41+
* public var val: Int
42+
* public var left: TreeNode?
43+
* public var right: TreeNode?
44+
* public init() { self.val = 0; self.left = nil; self.right = nil; }
45+
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
46+
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
47+
* self.val = val
48+
* self.left = left
49+
* self.right = right
50+
* }
51+
* }
52+
*/
53+
class Solution {
54+
func levelOrder(_ root: TreeNode?) -> [[Int]] {
55+
var result = [[Int]]()
56+
guard let root = root else {
57+
return result
58+
}
59+
60+
var queue: [TreeNode?] = [root, nil]
61+
var level = [Int]()
62+
63+
while !queue.isEmpty {
64+
let node = queue.removeFirst()
65+
if let node = node {
66+
level.append(node.val)
67+
if let left = node.left {
68+
queue.append(left)
69+
}
70+
if let right = node.right {
71+
queue.append(right)
72+
}
73+
} else {
74+
result.append(level)
75+
level = [Int]()
76+
if !queue.isEmpty {
77+
queue.append(nil)
78+
}
79+
}
80+
}
81+
return result
82+
}
83+
}
84+
```

0 commit comments

Comments
 (0)