Skip to content

Commit 6c3efb6

Browse files
committed
Improved swift readmes
1 parent 6abd495 commit 6c3efb6

File tree

6 files changed

+20
-339
lines changed
  • src/main/swift
    • g0001_0100/s0019_remove_nth_node_from_end_of_list
    • g0101_0200
      • s0102_binary_tree_level_order_traversal
      • s0104_maximum_depth_of_binary_tree
      • s0105_construct_binary_tree_from_preorder_and_inorder_traversal
      • s0114_flatten_binary_tree_to_linked_list
      • s0121_best_time_to_buy_and_sell_stock

6 files changed

+20
-339
lines changed

src/main/swift/g0001_0100/s0019_remove_nth_node_from_end_of_list/readme.md

Lines changed: 15 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -49,46 +49,32 @@ Here's the implementation:
4949

5050
```swift
5151
class Solution {
52-
func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {
53-
54-
guard ((head?.next) != nil), n > 0 else {return nil}
55-
52+
func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {
53+
guard ((head?.next) != nil), n > 0 else {return nil}
5654
var count = 0
57-
var current = head
58-
55+
var current = head
5956
while let currentNode = current{
6057
count += 1
6158
current = currentNode.next
62-
}
63-
59+
}
6460
current = head
65-
count = count - n + 1
66-
67-
var prev: ListNode?
68-
69-
while let currentNode = current{
70-
71-
count -= 1
72-
73-
if count == 0{
74-
75-
if prev == nil{
61+
count = count - n + 1
62+
var prev: ListNode?
63+
while let currentNode = current {
64+
count -= 1
65+
if count == 0 {
66+
if prev == nil {
7667
current = current?.next
7768
return current
78-
}else{
69+
} else {
7970
prev?.next = current?.next
8071
}
8172
break
82-
}
83-
73+
}
8474
prev = current
85-
current = current?.next
86-
87-
}
88-
89-
return head
90-
91-
75+
current = current?.next
76+
}
77+
return head
9278
}
9379
}
9480
```

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

Lines changed: 1 addition & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -27,76 +27,4 @@ Given the `root` of a binary tree, return _the level order traversal of its node
2727
**Constraints:**
2828

2929
* The number of nodes in the tree is in the range `[0, 2000]`.
30-
* `-1000 <= Node.val <= 1000`
31-
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-
34-
1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.
35-
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-
38-
3. **Initialize a queue**: Create a queue to store the nodes during BFS traversal.
39-
40-
4. **Check for null root**: Check if the root is null. If it is, return an empty list.
41-
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.
47-
48-
6. **Return the result**: After the BFS traversal is complete, return the list containing the level order traversal of the binary tree.
49-
50-
Here's the Java implementation:
51-
52-
```java
53-
import java.util.ArrayList;
54-
import java.util.LinkedList;
55-
import java.util.List;
56-
import java.util.Queue;
57-
58-
class Solution {
59-
public List<List<Integer>> levelOrder(TreeNode root) {
60-
List<List<Integer>> result = new ArrayList<>(); // Initialize list to store level order traversal
61-
if (root == null) return result; // Check for empty tree
62-
63-
Queue<TreeNode> queue = new LinkedList<>(); // Initialize queue for BFS traversal
64-
queue.offer(root); // Enqueue the root node
65-
66-
while (!queue.isEmpty()) {
67-
int levelSize = queue.size(); // Get the number of nodes in the current level
68-
List<Integer> level = new ArrayList<>(); // Initialize list for the current level
69-
70-
for (int i = 0; i < levelSize; i++) {
71-
TreeNode node = queue.poll(); // Dequeue the front node
72-
level.add(node.val); // Add node value to the current level list
73-
74-
// Enqueue the left and right children if they exist
75-
if (node.left != null) queue.offer(node.left);
76-
if (node.right != null) queue.offer(node.right);
77-
}
78-
79-
result.add(level); // Add the current level list to the result list
80-
}
81-
82-
return result; // Return the level order traversal
83-
}
84-
85-
// Definition for a TreeNode
86-
public class TreeNode {
87-
int val;
88-
TreeNode left;
89-
TreeNode right;
90-
91-
TreeNode() {}
92-
TreeNode(int val) { this.val = val; }
93-
TreeNode(int val, TreeNode left, TreeNode right) {
94-
this.val = val;
95-
this.left = left;
96-
this.right = right;
97-
}
98-
}
99-
}
100-
```
101-
102-
This implementation follows the steps outlined above and efficiently computes the level order traversal of the binary tree in Java using BFS.
30+
* `-1000 <= Node.val <= 1000`

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

Lines changed: 1 addition & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -35,46 +35,4 @@ A binary tree's **maximum depth** is the number of nodes along the longest path
3535
**Constraints:**
3636

3737
* The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.
38-
* `-100 <= Node.val <= 100`
39-
40-
To solve the "Maximum Depth of Binary Tree" problem in Java with a `Solution` class, we'll perform a depth-first search (DFS) traversal of the binary tree. Below are the steps:
41-
42-
1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.
43-
44-
2. **Create a `maxDepth` method**: This method takes the root node of the binary tree as input and returns its maximum depth.
45-
46-
3. **Check for null root**: Check if the root is null. If it is, return 0 as the depth.
47-
48-
4. **Perform DFS traversal**: Recursively compute the depth of the left and right subtrees. The maximum depth of the binary tree is the maximum depth of its left and right subtrees, plus 1 for the current node.
49-
50-
5. **Return the result**: After the DFS traversal is complete, return the maximum depth of the binary tree.
51-
52-
Here's the Java implementation:
53-
54-
```java
55-
class Solution {
56-
public int maxDepth(TreeNode root) {
57-
if (root == null) return 0; // Check for empty tree
58-
int leftDepth = maxDepth(root.left); // Compute depth of left subtree
59-
int rightDepth = maxDepth(root.right); // Compute depth of right subtree
60-
return Math.max(leftDepth, rightDepth) + 1; // Return maximum depth of left and right subtrees, plus 1 for the current node
61-
}
62-
63-
// Definition for a TreeNode
64-
public class TreeNode {
65-
int val;
66-
TreeNode left;
67-
TreeNode right;
68-
69-
TreeNode() {}
70-
TreeNode(int val) { this.val = val; }
71-
TreeNode(int val, TreeNode left, TreeNode right) {
72-
this.val = val;
73-
this.left = left;
74-
this.right = right;
75-
}
76-
}
77-
}
78-
```
79-
80-
This implementation follows the steps outlined above and efficiently computes the maximum depth of the binary tree in Java using DFS traversal.
38+
* `-100 <= Node.val <= 100`

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

Lines changed: 1 addition & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -26,80 +26,4 @@ Given two integer arrays `preorder` and `inorder` where `preorder` is the preord
2626
* `preorder` and `inorder` consist of **unique** values.
2727
* Each value of `inorder` also appears in `preorder`.
2828
* `preorder` is **guaranteed** to be the preorder traversal of the tree.
29-
* `inorder` is **guaranteed** to be the inorder traversal of the tree.
30-
31-
To solve the "Construct Binary Tree from Preorder and Inorder Traversal" problem in Java with a `Solution` class, we'll use a recursive approach. Below are the steps:
32-
33-
1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.
34-
35-
2. **Create a `buildTree` method**: This method takes two integer arrays, `preorder` and `inorder`, as input and returns the constructed binary tree.
36-
37-
3. **Check for empty arrays**: Check if either of the arrays `preorder` or `inorder` is empty. If so, return null, as there's no tree to construct.
38-
39-
4. **Define a helper method**: Define a recursive helper method `build` to construct the binary tree.
40-
- The method should take the indices representing the current subtree in both `preorder` and `inorder`.
41-
- The start and end indices in `preorder` represent the current subtree's preorder traversal.
42-
- The start and end indices in `inorder` represent the current subtree's inorder traversal.
43-
44-
5. **Base case**: If the start index of `preorder` is greater than the end index or if the start index of `inorder` is greater than the end index, return null.
45-
46-
6. **Find the root node**: The root node is the first element in the `preorder` array.
47-
48-
7. **Find the root's position in `inorder`**: Iterate through the `inorder` array to find the root's position.
49-
50-
8. **Recursively build left and right subtrees**:
51-
- Recursively call the `build` method for the left subtree with updated indices.
52-
- Recursively call the `build` method for the right subtree with updated indices.
53-
54-
9. **Return the root node**: After constructing the left and right subtrees, return the root node.
55-
56-
Here's the Java implementation:
57-
58-
```java
59-
class Solution {
60-
public TreeNode buildTree(int[] preorder, int[] inorder) {
61-
if (preorder.length == 0 || inorder.length == 0) return null; // Check for empty arrays
62-
return build(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1); // Construct binary tree
63-
}
64-
65-
// Recursive helper method to construct binary tree
66-
private TreeNode build(int[] preorder, int[] inorder, int preStart, int preEnd, int inStart, int inEnd) {
67-
if (preStart > preEnd || inStart > inEnd) return null; // Base case
68-
69-
int rootValue = preorder[preStart]; // Root node value
70-
TreeNode root = new TreeNode(rootValue); // Create root node
71-
72-
// Find root node's position in inorder array
73-
int rootIndex = 0;
74-
for (int i = inStart; i <= inEnd; i++) {
75-
if (inorder[i] == rootValue) {
76-
rootIndex = i;
77-
break;
78-
}
79-
}
80-
81-
// Recursively build left and right subtrees
82-
root.left = build(preorder, inorder, preStart + 1, preStart + rootIndex - inStart, inStart, rootIndex - 1);
83-
root.right = build(preorder, inorder, preStart + rootIndex - inStart + 1, preEnd, rootIndex + 1, inEnd);
84-
85-
return root; // Return root node
86-
}
87-
88-
// TreeNode definition
89-
public class TreeNode {
90-
int val;
91-
TreeNode left;
92-
TreeNode right;
93-
94-
TreeNode() {}
95-
TreeNode(int val) { this.val = val; }
96-
TreeNode(int val, TreeNode left, TreeNode right) {
97-
this.val = val;
98-
this.left = left;
99-
this.right = right;
100-
}
101-
}
102-
}
103-
```
104-
105-
This implementation follows the steps outlined above and efficiently constructs the binary tree from preorder and inorder traversals in Java.
29+
* `inorder` is **guaranteed** to be the inorder traversal of the tree.

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

Lines changed: 1 addition & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -32,81 +32,4 @@ Given the `root` of a binary tree, flatten the tree into a "linked list":
3232
* The number of nodes in the tree is in the range `[0, 2000]`.
3333
* `-100 <= Node.val <= 100`
3434

35-
**Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)?
36-
37-
To solve the "Flatten Binary Tree to Linked List" problem in Java with a `Solution` class, we'll use a recursive approach. Below are the steps:
38-
39-
1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.
40-
41-
2. **Create a `flatten` method**: This method takes the root node of the binary tree as input and flattens the tree into a linked list using preorder traversal.
42-
43-
3. **Check for null root**: Check if the root is null. If so, there's no tree to flatten, so return.
44-
45-
4. **Recursively flatten the tree**: Define a recursive helper method `flattenTree` to perform the flattening.
46-
- The method should take the current node as input.
47-
- Perform a preorder traversal of the tree.
48-
- For each node, if it has a left child:
49-
- Find the rightmost node in the left subtree.
50-
- Attach the right subtree of the current node to the right of the rightmost node.
51-
- Move the left subtree to the right subtree position.
52-
- Set the left child of the current node to null.
53-
- Recursively call the method for the right child.
54-
55-
5. **Call the helper method**: Call the `flattenTree` method with the root node.
56-
57-
Here's the Java implementation:
58-
59-
```java
60-
class Solution {
61-
public void flatten(TreeNode root) {
62-
if (root == null) return; // Check for empty tree
63-
flattenTree(root); // Flatten the tree
64-
}
65-
66-
// Recursive helper method to flatten the tree
67-
private void flattenTree(TreeNode node) {
68-
if (node == null) return;
69-
70-
// Flatten left subtree
71-
flattenTree(node.left);
72-
73-
// Flatten right subtree
74-
flattenTree(node.right);
75-
76-
// Save right subtree
77-
TreeNode rightSubtree = node.right;
78-
79-
// Attach left subtree to the right of the current node
80-
node.right = node.left;
81-
82-
// Set left child to null
83-
node.left = null;
84-
85-
// Move to the rightmost node of the flattened left subtree
86-
TreeNode current = node;
87-
while (current.right != null) {
88-
current = current.right;
89-
}
90-
91-
// Attach the saved right subtree to the right of the rightmost node
92-
current.right = rightSubtree;
93-
}
94-
95-
// TreeNode definition
96-
public class TreeNode {
97-
int val;
98-
TreeNode left;
99-
TreeNode right;
100-
101-
TreeNode() {}
102-
TreeNode(int val) { this.val = val; }
103-
TreeNode(int val, TreeNode left, TreeNode right) {
104-
this.val = val;
105-
this.left = left;
106-
this.right = right;
107-
}
108-
}
109-
}
110-
```
111-
112-
This implementation follows the steps outlined above and efficiently flattens the binary tree into a linked list using preorder traversal in Java.
35+
**Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)?

0 commit comments

Comments
 (0)