Skip to content

Commit

Permalink
Added solutions 102-138
Browse files Browse the repository at this point in the history
  • Loading branch information
javadev authored Mar 31, 2024
1 parent fc3daf4 commit 9b3e99d
Show file tree
Hide file tree
Showing 10 changed files with 600 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,76 @@ Given the `root` of a binary tree, return _the level order traversal of its node
**Constraints:**

* The number of nodes in the tree is in the range `[0, 2000]`.
* `-1000 <= Node.val <= 1000`
* `-1000 <= Node.val <= 1000`

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:

1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.

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.

3. **Initialize a queue**: Create a queue to store the nodes during BFS traversal.

4. **Check for null root**: Check if the root is null. If it is, return an empty list.

5. **Perform BFS traversal**: Enqueue the root node into the queue. While the queue is not empty:
- Dequeue the front node from the queue.
- Add the value of the dequeued node to the current level list.
- Enqueue the left and right children of the dequeued node if they exist.
- Move to the next level when all nodes in the current level are processed.

6. **Return the result**: After the BFS traversal is complete, return the list containing the level order traversal of the binary tree.

Here's the Java implementation:

```java
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>(); // Initialize list to store level order traversal
if (root == null) return result; // Check for empty tree

Queue<TreeNode> queue = new LinkedList<>(); // Initialize queue for BFS traversal
queue.offer(root); // Enqueue the root node

while (!queue.isEmpty()) {
int levelSize = queue.size(); // Get the number of nodes in the current level
List<Integer> level = new ArrayList<>(); // Initialize list for the current level

for (int i = 0; i < levelSize; i++) {
TreeNode node = queue.poll(); // Dequeue the front node
level.add(node.val); // Add node value to the current level list

// Enqueue the left and right children if they exist
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}

result.add(level); // Add the current level list to the result list
}

return result; // Return the level order traversal
}

// Definition for a TreeNode
public class TreeNode {
int val;
TreeNode left;
TreeNode right;

TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
}
```

This implementation follows the steps outlined above and efficiently computes the level order traversal of the binary tree in Java using BFS.
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,46 @@ A binary tree's **maximum depth** is the number of nodes along the longest path
**Constraints:**

* The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.
* `-100 <= Node.val <= 100`
* `-100 <= Node.val <= 100`

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:

1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.

2. **Create a `maxDepth` method**: This method takes the root node of the binary tree as input and returns its maximum depth.

3. **Check for null root**: Check if the root is null. If it is, return 0 as the depth.

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.

5. **Return the result**: After the DFS traversal is complete, return the maximum depth of the binary tree.

Here's the Java implementation:

```java
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0; // Check for empty tree
int leftDepth = maxDepth(root.left); // Compute depth of left subtree
int rightDepth = maxDepth(root.right); // Compute depth of right subtree
return Math.max(leftDepth, rightDepth) + 1; // Return maximum depth of left and right subtrees, plus 1 for the current node
}

// Definition for a TreeNode
public class TreeNode {
int val;
TreeNode left;
TreeNode right;

TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
}
```

This implementation follows the steps outlined above and efficiently computes the maximum depth of the binary tree in Java using DFS traversal.
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,80 @@ Given two integer arrays `preorder` and `inorder` where `preorder` is the preord
* `preorder` and `inorder` consist of **unique** values.
* Each value of `inorder` also appears in `preorder`.
* `preorder` is **guaranteed** to be the preorder traversal of the tree.
* `inorder` is **guaranteed** to be the inorder traversal of the tree.
* `inorder` is **guaranteed** to be the inorder traversal of the tree.

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:

1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.

2. **Create a `buildTree` method**: This method takes two integer arrays, `preorder` and `inorder`, as input and returns the constructed binary tree.

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.

4. **Define a helper method**: Define a recursive helper method `build` to construct the binary tree.
- The method should take the indices representing the current subtree in both `preorder` and `inorder`.
- The start and end indices in `preorder` represent the current subtree's preorder traversal.
- The start and end indices in `inorder` represent the current subtree's inorder traversal.

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.

6. **Find the root node**: The root node is the first element in the `preorder` array.

7. **Find the root's position in `inorder`**: Iterate through the `inorder` array to find the root's position.

8. **Recursively build left and right subtrees**:
- Recursively call the `build` method for the left subtree with updated indices.
- Recursively call the `build` method for the right subtree with updated indices.

9. **Return the root node**: After constructing the left and right subtrees, return the root node.

Here's the Java implementation:

```java
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder.length == 0 || inorder.length == 0) return null; // Check for empty arrays
return build(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1); // Construct binary tree
}

// Recursive helper method to construct binary tree
private TreeNode build(int[] preorder, int[] inorder, int preStart, preEnd, int inStart, int inEnd) {
if (preStart > preEnd || inStart > inEnd) return null; // Base case

int rootValue = preorder[preStart]; // Root node value
TreeNode root = new TreeNode(rootValue); // Create root node

// Find root node's position in inorder array
int rootIndex = 0;
for (int i = inStart; i <= inEnd; i++) {
if (inorder[i] == rootValue) {
rootIndex = i;
break;
}
}

// Recursively build left and right subtrees
root.left = build(preorder, inorder, preStart + 1, preStart + rootIndex - inStart, inStart, rootIndex - 1);
root.right = build(preorder, inorder, preStart + rootIndex - inStart + 1, preEnd, rootIndex + 1, inEnd);

return root; // Return root node
}

// TreeNode definition
public class TreeNode {
int val;
TreeNode left;
TreeNode right;

TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
}
```

This implementation follows the steps outlined above and efficiently constructs the binary tree from preorder and inorder traversals in Java.
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,81 @@ Given the `root` of a binary tree, flatten the tree into a "linked list":
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-100 <= Node.val <= 100`

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

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:

1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.

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.

3. **Check for null root**: Check if the root is null. If so, there's no tree to flatten, so return.

4. **Recursively flatten the tree**: Define a recursive helper method `flattenTree` to perform the flattening.
- The method should take the current node as input.
- Perform a preorder traversal of the tree.
- For each node, if it has a left child:
- Find the rightmost node in the left subtree.
- Attach the right subtree of the current node to the right of the rightmost node.
- Move the left subtree to the right subtree position.
- Set the left child of the current node to null.
- Recursively call the method for the right child.

5. **Call the helper method**: Call the `flattenTree` method with the root node.

Here's the Java implementation:

```java
class Solution {
public void flatten(TreeNode root) {
if (root == null) return; // Check for empty tree
flattenTree(root); // Flatten the tree
}

// Recursive helper method to flatten the tree
private void flattenTree(TreeNode node) {
if (node == null) return;

// Flatten left subtree
flattenTree(node.left);

// Flatten right subtree
flattenTree(node.right);

// Save right subtree
TreeNode rightSubtree = node.right;

// Attach left subtree to the right of the current node
node.right = node.left;

// Set left child to null
node.left = null;

// Move to the rightmost node of the flattened left subtree
TreeNode current = node;
while (current.right != null) {
current = current.right;
}

// Attach the saved right subtree to the right of the rightmost node
current.right = rightSubtree;
}

// TreeNode definition
public class TreeNode {
int val;
TreeNode left;
TreeNode right;

TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
}
```

This implementation follows the steps outlined above and efficiently flattens the binary tree into a linked list using preorder traversal in Java.
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,42 @@ Return _the maximum profit you can achieve from this transaction_. If you cannot
**Constraints:**

* <code>1 <= prices.length <= 10<sup>5</sup></code>
* <code>0 <= prices[i] <= 10<sup>4</sup></code>
* <code>0 <= prices[i] <= 10<sup>4</sup></code>

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:

1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.

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.

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.

4. **Iterate through the prices array**:
- For each price in the array:
- Update `minPrice` to the minimum of the current price and `minPrice`.
- Update `maxProfit` to the maximum of the current profit (price - `minPrice`) and `maxProfit`.

5. **Return the maximum profit**: After iterating through the entire array, return `maxProfit`.

Here's the Java implementation:

```java
class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length <= 1) return 0; // Check for empty array or single element

int minPrice = prices[0]; // Initialize minPrice to the first price
int maxProfit = 0; // Initialize maxProfit to 0

// Iterate through the prices array
for (int i = 1; i < prices.length; i++) {
minPrice = Math.min(minPrice, prices[i]); // Update minPrice
maxProfit = Math.max(maxProfit, prices[i] - minPrice); // Update maxProfit
}

return maxProfit; // Return the maximum profit
}
}
```

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.
Loading

0 comments on commit 9b3e99d

Please sign in to comment.