Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit f81690a

Browse files
committedJul 20, 2024·
Updated readme
1 parent 8655ad3 commit f81690a

File tree

7 files changed

+478
-606
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

7 files changed

+478
-606
lines changed
 

‎README.md

Lines changed: 307 additions & 307 deletions
Large diffs are not rendered by default.

‎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
@@ -52,46 +52,32 @@ Here's the implementation:
5252

5353
```swift
5454
class Solution {
55-
func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {
56-
57-
guard ((head?.next) != nil), n > 0 else {return nil}
58-
55+
func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {
56+
guard ((head?.next) != nil), n > 0 else {return nil}
5957
var count = 0
60-
var current = head
61-
58+
var current = head
6259
while let currentNode = current{
6360
count += 1
6461
current = currentNode.next
65-
}
66-
62+
}
6763
current = head
68-
count = count - n + 1
69-
70-
var prev: ListNode?
71-
72-
while let currentNode = current{
73-
74-
count -= 1
75-
76-
if count == 0{
77-
78-
if prev == nil{
64+
count = count - n + 1
65+
var prev: ListNode?
66+
while let currentNode = current {
67+
count -= 1
68+
if count == 0 {
69+
if prev == nil {
7970
current = current?.next
8071
return current
81-
}else{
72+
} else {
8273
prev?.next = current?.next
8374
}
8475
break
85-
}
86-
76+
}
8777
prev = current
88-
current = current?.next
89-
90-
}
91-
92-
return head
93-
94-
78+
current = current?.next
79+
}
80+
return head
9581
}
9682
}
9783
```

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

Lines changed: 43 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -32,74 +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.
52-
53-
Here's the Java implementation:
54-
55-
```java
56-
import java.util.ArrayList;
57-
import java.util.LinkedList;
58-
import java.util.List;
59-
import java.util.Queue;
60-
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+
*/
6153
class Solution {
62-
public List<List<Integer>> levelOrder(TreeNode root) {
63-
List<List<Integer>> result = new ArrayList<>(); // Initialize list to store level order traversal
64-
if (root == null) return result; // Check for empty tree
65-
66-
Queue<TreeNode> queue = new LinkedList<>(); // Initialize queue for BFS traversal
67-
queue.offer(root); // Enqueue the root node
68-
69-
while (!queue.isEmpty()) {
70-
int levelSize = queue.size(); // Get the number of nodes in the current level
71-
List<Integer> level = new ArrayList<>(); // Initialize list for the current level
72-
73-
for (int i = 0; i < levelSize; i++) {
74-
TreeNode node = queue.poll(); // Dequeue the front node
75-
level.add(node.val); // Add node value to the current level list
76-
77-
// Enqueue the left and right children if they exist
78-
if (node.left != null) queue.offer(node.left);
79-
if (node.right != null) queue.offer(node.right);
80-
}
81-
82-
result.add(level); // Add the current level list to the result list
54+
func levelOrder(_ root: TreeNode?) -> [[Int]] {
55+
var result = [[Int]]()
56+
guard let root = root else {
57+
return result
8358
}
8459

85-
return result; // Return the level order traversal
86-
}
87-
88-
// Definition for a TreeNode
89-
public class TreeNode {
90-
int val;
91-
TreeNode left;
92-
TreeNode right;
60+
var queue: [TreeNode?] = [root, nil]
61+
var level = [Int]()
9362

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;
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+
}
10080
}
81+
return result
10182
}
10283
}
103-
```
104-
105-
This implementation follows the steps outlined above and efficiently computes the level order traversal of the binary tree in Java using BFS.
84+
```

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

Lines changed: 24 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -40,44 +40,31 @@ A binary tree's **maximum depth** is the number of nodes along the longest path
4040
* The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.
4141
* `-100 <= Node.val <= 100`
4242

43-
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:
44-
45-
1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.
46-
47-
2. **Create a `maxDepth` method**: This method takes the root node of the binary tree as input and returns its maximum depth.
48-
49-
3. **Check for null root**: Check if the root is null. If it is, return 0 as the depth.
50-
51-
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.
52-
53-
5. **Return the result**: After the DFS traversal is complete, return the maximum depth of the binary tree.
54-
55-
Here's the Java implementation:
56-
57-
```java
43+
## Solution
44+
45+
```swift
46+
/**
47+
* Definition for a binary tree node.
48+
* public class TreeNode {
49+
* public var val: Int
50+
* public var left: TreeNode?
51+
* public var right: TreeNode?
52+
* public init() { self.val = 0; self.left = nil; self.right = nil; }
53+
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
54+
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
55+
* self.val = val
56+
* self.left = left
57+
* self.right = right
58+
* }
59+
* }
60+
*/
5861
class Solution {
59-
public int maxDepth(TreeNode root) {
60-
if (root == null) return 0; // Check for empty tree
61-
int leftDepth = maxDepth(root.left); // Compute depth of left subtree
62-
int rightDepth = maxDepth(root.right); // Compute depth of right subtree
63-
return Math.max(leftDepth, rightDepth) + 1; // Return maximum depth of left and right subtrees, plus 1 for the current node
64-
}
65-
66-
// Definition for a TreeNode
67-
public class TreeNode {
68-
int val;
69-
TreeNode left;
70-
TreeNode right;
71-
72-
TreeNode() {}
73-
TreeNode(int val) { this.val = val; }
74-
TreeNode(int val, TreeNode left, TreeNode right) {
75-
this.val = val;
76-
this.left = left;
77-
this.right = right;
62+
func maxDepth(_ root: TreeNode?) -> Int {
63+
guard let root else {
64+
return 0
7865
}
66+
67+
return 1 + max(maxDepth(root.left), maxDepth(root.right))
7968
}
8069
}
81-
```
82-
83-
This implementation follows the steps outlined above and efficiently computes the maximum depth of the binary tree in Java using DFS traversal.
70+
```

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

Lines changed: 37 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -31,78 +31,45 @@ Given two integer arrays `preorder` and `inorder` where `preorder` is the preord
3131
* `preorder` is **guaranteed** to be the preorder traversal of the tree.
3232
* `inorder` is **guaranteed** to be the inorder traversal of the tree.
3333

34-
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:
35-
36-
1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.
37-
38-
2. **Create a `buildTree` method**: This method takes two integer arrays, `preorder` and `inorder`, as input and returns the constructed binary tree.
39-
40-
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.
41-
42-
4. **Define a helper method**: Define a recursive helper method `build` to construct the binary tree.
43-
- The method should take the indices representing the current subtree in both `preorder` and `inorder`.
44-
- The start and end indices in `preorder` represent the current subtree's preorder traversal.
45-
- The start and end indices in `inorder` represent the current subtree's inorder traversal.
46-
47-
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.
48-
49-
6. **Find the root node**: The root node is the first element in the `preorder` array.
50-
51-
7. **Find the root's position in `inorder`**: Iterate through the `inorder` array to find the root's position.
52-
53-
8. **Recursively build left and right subtrees**:
54-
- Recursively call the `build` method for the left subtree with updated indices.
55-
- Recursively call the `build` method for the right subtree with updated indices.
56-
57-
9. **Return the root node**: After constructing the left and right subtrees, return the root node.
58-
59-
Here's the Java implementation:
60-
61-
```java
34+
## Solution
35+
36+
```swift
37+
/**
38+
* Definition for a binary tree node.
39+
* public class TreeNode {
40+
* public var val: Int
41+
* public var left: TreeNode?
42+
* public var right: TreeNode?
43+
* public init() { self.val = 0; self.left = nil; self.right = nil; }
44+
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
45+
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
46+
* self.val = val
47+
* self.left = left
48+
* self.right = right
49+
* }
50+
* }
51+
*/
6252
class Solution {
63-
public TreeNode buildTree(int[] preorder, int[] inorder) {
64-
if (preorder.length == 0 || inorder.length == 0) return null; // Check for empty arrays
65-
return build(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1); // Construct binary tree
66-
}
67-
68-
// Recursive helper method to construct binary tree
69-
private TreeNode build(int[] preorder, int[] inorder, int preStart, int preEnd, int inStart, int inEnd) {
70-
if (preStart > preEnd || inStart > inEnd) return null; // Base case
71-
72-
int rootValue = preorder[preStart]; // Root node value
73-
TreeNode root = new TreeNode(rootValue); // Create root node
74-
75-
// Find root node's position in inorder array
76-
int rootIndex = 0;
77-
for (int i = inStart; i <= inEnd; i++) {
78-
if (inorder[i] == rootValue) {
79-
rootIndex = i;
80-
break;
81-
}
53+
func buildTree(_ preorder: [Int], _ inorder: [Int]) -> TreeNode? {
54+
let n = preorder.count
55+
var preIndex = 0
56+
var map: [Int:Int] = [:]
57+
for (i, val) in inorder.enumerated() {
58+
map[val] = i
8259
}
83-
84-
// Recursively build left and right subtrees
85-
root.left = build(preorder, inorder, preStart + 1, preStart + rootIndex - inStart, inStart, rootIndex - 1);
86-
root.right = build(preorder, inorder, preStart + rootIndex - inStart + 1, preEnd, rootIndex + 1, inEnd);
87-
88-
return root; // Return root node
89-
}
90-
91-
// TreeNode definition
92-
public class TreeNode {
93-
int val;
94-
TreeNode left;
95-
TreeNode right;
96-
97-
TreeNode() {}
98-
TreeNode(int val) { this.val = val; }
99-
TreeNode(int val, TreeNode left, TreeNode right) {
100-
this.val = val;
101-
this.left = left;
102-
this.right = right;
60+
func findIndex(_ value: Int) -> Int {
61+
return map[value] ?? -1
62+
}
63+
func build(_ inStart: Int, _ inEnd: Int) -> TreeNode? {
64+
guard inStart <= inEnd else { return nil }
65+
let root = TreeNode(preorder[preIndex])
66+
let inIndex = findIndex(root.val)
67+
preIndex += 1
68+
root.left = build(inStart, inIndex - 1)
69+
root.right = build(inIndex + 1, inEnd)
70+
return root
10371
}
72+
return build(0, n - 1)
10473
}
10574
}
106-
```
107-
108-
This implementation follows the steps outlined above and efficiently constructs the binary tree from preorder and inorder traversals in Java.
75+
```

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

Lines changed: 38 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -37,79 +37,47 @@ Given the `root` of a binary tree, flatten the tree into a "linked list":
3737

3838
**Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)?
3939

40-
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:
41-
42-
1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.
43-
44-
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.
45-
46-
3. **Check for null root**: Check if the root is null. If so, there's no tree to flatten, so return.
47-
48-
4. **Recursively flatten the tree**: Define a recursive helper method `flattenTree` to perform the flattening.
49-
- The method should take the current node as input.
50-
- Perform a preorder traversal of the tree.
51-
- For each node, if it has a left child:
52-
- Find the rightmost node in the left subtree.
53-
- Attach the right subtree of the current node to the right of the rightmost node.
54-
- Move the left subtree to the right subtree position.
55-
- Set the left child of the current node to null.
56-
- Recursively call the method for the right child.
57-
58-
5. **Call the helper method**: Call the `flattenTree` method with the root node.
59-
60-
Here's the Java implementation:
61-
62-
```java
40+
## Solution
41+
42+
```swift
43+
/**
44+
* Definition for a binary tree node.
45+
* public class TreeNode {
46+
* public var val: Int
47+
* public var left: TreeNode?
48+
* public var right: TreeNode?
49+
* public init() { self.val = 0; self.left = nil; self.right = nil; }
50+
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
51+
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
52+
* self.val = val
53+
* self.left = left
54+
* self.right = right
55+
* }
56+
* }
57+
*/
6358
class Solution {
64-
public void flatten(TreeNode root) {
65-
if (root == null) return; // Check for empty tree
66-
flattenTree(root); // Flatten the tree
67-
}
68-
69-
// Recursive helper method to flatten the tree
70-
private void flattenTree(TreeNode node) {
71-
if (node == null) return;
72-
73-
// Flatten left subtree
74-
flattenTree(node.left);
75-
76-
// Flatten right subtree
77-
flattenTree(node.right);
78-
79-
// Save right subtree
80-
TreeNode rightSubtree = node.right;
81-
82-
// Attach left subtree to the right of the current node
83-
node.right = node.left;
84-
85-
// Set left child to null
86-
node.left = null;
87-
88-
// Move to the rightmost node of the flattened left subtree
89-
TreeNode current = node;
90-
while (current.right != null) {
91-
current = current.right;
59+
func flatten(_ root: TreeNode?) {
60+
var values: [Int] = []
61+
getAllValues(root, &values)
62+
let linkedList = TreeNode()
63+
var currLink: TreeNode? = linkedList
64+
for index in 0..<values.count {
65+
currLink?.right = TreeNode(values[index])
66+
currLink = currLink?.right
9267
}
93-
94-
// Attach the saved right subtree to the right of the rightmost node
95-
current.right = rightSubtree;
68+
root?.right = linkedList.right?.right
69+
root?.left = nil
9670
}
97-
98-
// TreeNode definition
99-
public class TreeNode {
100-
int val;
101-
TreeNode left;
102-
TreeNode right;
103-
104-
TreeNode() {}
105-
TreeNode(int val) { this.val = val; }
106-
TreeNode(int val, TreeNode left, TreeNode right) {
107-
this.val = val;
108-
this.left = left;
109-
this.right = right;
71+
72+
private func getAllValues(_ curr: TreeNode?, _ values: inout [Int]) {
73+
guard let curr = curr else { return }
74+
values.append(curr.val)
75+
if let left = curr.left {
76+
getAllValues(left, &values)
77+
}
78+
if let right = curr.right {
79+
getAllValues(right, &values)
11080
}
11181
}
11282
}
113-
```
114-
115-
This implementation follows the steps outlined above and efficiently flattens the binary tree into a linked list using preorder traversal in Java.
83+
```

‎src/main/swift/g0101_0200/s0121_best_time_to_buy_and_sell_stock/readme.md

Lines changed: 14 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -32,40 +32,25 @@ Return _the maximum profit you can achieve from this transaction_. If you cannot
3232
* <code>1 <= prices.length <= 10<sup>5</sup></code>
3333
* <code>0 <= prices[i] <= 10<sup>4</sup></code>
3434

35-
To solve the "Best Time to Buy and Sell Stock" problem in Java with a `Solution` class, we'll use a greedy algorithm. Below are the steps:
35+
## Solution
3636

37-
1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.
38-
39-
2. **Create a `maxProfit` method**: This method takes an array `prices` as input and returns the maximum profit that can be achieved by buying and selling the stock.
40-
41-
3. **Initialize variables**: Initialize two variables, `minPrice` to store the minimum price seen so far and `maxProfit` to store the maximum profit seen so far. Initialize `maxProfit` to 0.
42-
43-
4. **Iterate through the prices array**:
44-
- For each price in the array:
45-
- Update `minPrice` to the minimum of the current price and `minPrice`.
46-
- Update `maxProfit` to the maximum of the current profit (price - `minPrice`) and `maxProfit`.
47-
48-
5. **Return the maximum profit**: After iterating through the entire array, return `maxProfit`.
49-
50-
Here's the Java implementation:
51-
52-
```java
37+
```swift
5338
class Solution {
54-
public int maxProfit(int[] prices) {
55-
if (prices == null || prices.length <= 1) return 0; // Check for empty array or single element
39+
func maxProfit(_ prices: [Int]) -> Int {
40+
guard prices.count > 0 else { return 0 }
5641

57-
int minPrice = prices[0]; // Initialize minPrice to the first price
58-
int maxProfit = 0; // Initialize maxProfit to 0
42+
var maxProfit = 0
43+
var minPrice = prices[0]
5944

60-
// Iterate through the prices array
61-
for (int i = 1; i < prices.length; i++) {
62-
minPrice = Math.min(minPrice, prices[i]); // Update minPrice
63-
maxProfit = Math.max(maxProfit, prices[i] - minPrice); // Update maxProfit
45+
for i in 1..<prices.count {
46+
if prices[i] > minPrice {
47+
maxProfit = max(maxProfit, prices[i] - minPrice)
48+
} else {
49+
minPrice = prices[i]
50+
}
6451
}
6552

66-
return maxProfit; // Return the maximum profit
53+
return maxProfit
6754
}
6855
}
69-
```
70-
71-
This implementation follows the steps outlined above and efficiently calculates the maximum profit that can be achieved by buying and selling the stock in Java.
56+
```

0 commit comments

Comments
 (0)
Please sign in to comment.