Skip to content

Commit 9e98f74

Browse files
committed
Improved tasks 102, 104, 105, 114, 121
1 parent 421e82f commit 9e98f74

File tree

5 files changed

+114
-261
lines changed
  • src/main/swift/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

5 files changed

+114
-261
lines changed

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

+1-55
Original file line numberDiff line numberDiff line change
@@ -48,58 +48,4 @@ To solve the "Binary Tree Level Order Traversal" problem in Java with a `Solutio
4848
- Enqueue the left and right children of the dequeued node if they exist.
4949
- Move to the next level when all nodes in the current level are processed.
5050

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-
61-
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
83-
}
84-
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;
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 computes the level order traversal of the binary tree in Java using BFS.
51+
6. **Return the result**: After the BFS traversal is complete, return the list containing the level order traversal of the binary tree.

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

+24-37
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

+37-70
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

+38-70
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+
```

0 commit comments

Comments
 (0)