Skip to content

Commit cbb1ffe

Browse files
committed
Added solutions 102-138
1 parent fc3daf4 commit cbb1ffe

File tree

10 files changed

+610
-10
lines changed
  • src/main/java/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
    • s0124_binary_tree_maximum_path_sum
    • s0128_longest_consecutive_sequence
    • s0131_palindrome_partitioning
    • s0136_single_number
    • s0138_copy_list_with_random_pointer

10 files changed

+610
-10
lines changed

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

+74-1
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,77 @@ 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`
30+
* `-1000 <= Node.val <= 1000`
31+
32+
To solve this problem in Java with a `Solution` class, we'll use a breadth-first search (BFS) traversal approach. 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. **Check for null root**: Check if the root is null. If so, return an empty list since there are no nodes to traverse.
39+
40+
4. **Initialize a queue**: We'll use a queue to perform BFS traversal. Add the root node to the queue.
41+
42+
5. **Traverse the tree level by level**:
43+
- Start a loop that continues until the queue is empty.
44+
- Inside the loop, for each level, get the size of the queue (number of nodes at the current level).
45+
- Create a list to store the node values at the current level.
46+
- Iterate through all nodes at the current level:
47+
- Poll a node from the queue.
48+
- Add its value to the list.
49+
- If the node has left or right children, add them to the queue.
50+
- After processing all nodes at the current level, add the list of node values to the result list.
51+
52+
6. **Return the result**: After traversing the entire tree, return the result containing the level order traversal.
53+
54+
Here's the Java implementation:
55+
56+
```java
57+
import java.util.*;
58+
59+
class Solution {
60+
public List<List<Integer>> levelOrder(TreeNode root) {
61+
List<List<Integer>> result = new ArrayList<>();
62+
63+
if (root == null) return result; // Check for empty tree
64+
65+
Queue<TreeNode> queue = new LinkedList<>();
66+
queue.offer(root); // Add root to the queue
67+
68+
while (!queue.isEmpty()) {
69+
int levelSize = queue.size(); // Get the number of nodes at the current level
70+
List<Integer> levelNodes = new ArrayList<>(); // List to store node values at current level
71+
72+
for (int i = 0; i < levelSize; i++) {
73+
TreeNode node = queue.poll(); // Remove node from the queue
74+
levelNodes.add(node.val); // Add its value to the list
75+
76+
// Add left and right children to the queue if they exist
77+
if (node.left != null) queue.offer(node.left);
78+
if (node.right != null) queue.offer(node.right);
79+
}
80+
result.add(levelNodes); // Add list of node values at current level to result
81+
}
82+
83+
return result;
84+
}
85+
86+
// TreeNode definition
87+
public class TreeNode {
88+
int val;
89+
TreeNode left;
90+
TreeNode right;
91+
92+
TreeNode() {}
93+
TreeNode(int val) { this.val = val; }
94+
TreeNode(int val, TreeNode left, TreeNode right) {
95+
this.val = val;
96+
this.left = left;
97+
this.right = right;
98+
}
99+
}
100+
}
101+
```
102+
103+
This implementation follows the steps outlined above and efficiently solves the problem of binary tree level order traversal in Java.

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

+52-1
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,55 @@ 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`
38+
* `-100 <= Node.val <= 100`
39+
40+
To solve this problem in Java with a `Solution` class, we'll use a depth-first search (DFS) traversal 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 `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 so, return 0, as an empty tree has a maximum depth of 0.
47+
48+
4. **Recursively calculate the maximum depth**: Define a helper method `dfs` to recursively calculate the maximum depth of the binary tree.
49+
- If the current node is null, return 0.
50+
- Otherwise, recursively calculate the maximum depth of the left and right subtrees.
51+
- Return the maximum depth of the left and right subtrees, plus 1 (to account for the current node).
52+
53+
5. **Return the maximum depth**: After traversing the entire tree, return the maximum depth calculated.
54+
55+
Here's the Java implementation:
56+
57+
```java
58+
class Solution {
59+
public int maxDepth(TreeNode root) {
60+
if (root == null) return 0; // Check for empty tree
61+
return dfs(root); // Recursively calculate maximum depth
62+
}
63+
64+
// Helper method to recursively calculate maximum depth
65+
private int dfs(TreeNode node) {
66+
if (node == null) return 0;
67+
int leftDepth = dfs(node.left); // Calculate maximum depth of left subtree
68+
int rightDepth = dfs(node.right); // Calculate maximum depth of right subtree
69+
return Math.max(leftDepth, rightDepth) + 1; // Return maximum depth plus 1 for current node
70+
}
71+
72+
// TreeNode definition
73+
public class TreeNode {
74+
int val;
75+
TreeNode left;
76+
TreeNode right;
77+
78+
TreeNode() {}
79+
TreeNode(int val) { this.val = val; }
80+
TreeNode(int val, TreeNode left, TreeNode right) {
81+
this.val = val;
82+
this.left = left;
83+
this.right = right;
84+
}
85+
}
86+
}
87+
```
88+
89+
This implementation follows the steps outlined above and efficiently solves the problem of finding the maximum depth of a binary tree in Java.

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

+77-1
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,80 @@ 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.
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, 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.

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

+78-1
Original file line numberDiff line numberDiff line change
@@ -32,4 +32,81 @@ 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)?
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.

src/main/java/g0101_0200/s0121_best_time_to_buy_and_sell_stock/readme.md

+39-1
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,42 @@ Return _the maximum profit you can achieve from this transaction_. If you cannot
2727
**Constraints:**
2828

2929
* <code>1 <= prices.length <= 10<sup>5</sup></code>
30-
* <code>0 <= prices[i] <= 10<sup>4</sup></code>
30+
* <code>0 <= prices[i] <= 10<sup>4</sup></code>
31+
32+
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:
33+
34+
1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.
35+
36+
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.
37+
38+
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.
39+
40+
4. **Iterate through the prices array**:
41+
- For each price in the array:
42+
- Update `minPrice` to the minimum of the current price and `minPrice`.
43+
- Update `maxProfit` to the maximum of the current profit (price - `minPrice`) and `maxProfit`.
44+
45+
5. **Return the maximum profit**: After iterating through the entire array, return `maxProfit`.
46+
47+
Here's the Java implementation:
48+
49+
```java
50+
class Solution {
51+
public int maxProfit(int[] prices) {
52+
if (prices == null || prices.length <= 1) return 0; // Check for empty array or single element
53+
54+
int minPrice = prices[0]; // Initialize minPrice to the first price
55+
int maxProfit = 0; // Initialize maxProfit to 0
56+
57+
// Iterate through the prices array
58+
for (int i = 1; i < prices.length; i++) {
59+
minPrice = Math.min(minPrice, prices[i]); // Update minPrice
60+
maxProfit = Math.max(maxProfit, prices[i] - minPrice); // Update maxProfit
61+
}
62+
63+
return maxProfit; // Return the maximum profit
64+
}
65+
}
66+
```
67+
68+
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.

0 commit comments

Comments
 (0)