Skip to content

Commit f81690a

Browse files
committed
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+
```

0 commit comments

Comments
 (0)