Skip to content

Commit 9b40015

Browse files
committed
Added cpp tasks 96-155
1 parent 57f259f commit 9b40015

File tree

21 files changed

+1882
-0
lines changed

21 files changed

+1882
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 96\. Unique Binary Search Trees
5+
6+
Medium
7+
8+
Given an integer `n`, return _the number of structurally unique **BST'**s (binary search trees) which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`.
9+
10+
**Example 1:**
11+
12+
![](https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg)
13+
14+
**Input:** n = 3
15+
16+
**Output:** 5
17+
18+
**Example 2:**
19+
20+
**Input:** n = 1
21+
22+
**Output:** 1
23+
24+
**Constraints:**
25+
26+
* `1 <= n <= 19`
27+
28+
To solve the "Unique Binary Search Trees" problem in Java with the Solution class, follow these steps:
29+
30+
1. Define a method `numTrees` in the `Solution` class that takes an integer `n` as input and returns the number of structurally unique BSTs (binary search trees) with exactly `n` nodes.
31+
2. Implement a dynamic programming approach to solve the problem:
32+
- Create an array `dp` of size `n + 1` to store the number of unique BSTs for each number of nodes from 0 to `n`.
33+
- Initialize `dp[0] = 1` and `dp[1] = 1`, as there is only one unique BST for 0 and 1 node(s).
34+
- Use a nested loop to calculate `dp[i]` for each `i` from 2 to `n`.
35+
- For each `i`, calculate `dp[i]` by summing up the products of `dp[j]` and `dp[i - j - 1]` for all possible values of `j` from 0 to `i - 1`.
36+
- Return `dp[n]`, which represents the number of unique BSTs with `n` nodes.
37+
38+
Here's the implementation of the `numTrees` method in Java:
39+
40+
```java
41+
class Solution {
42+
public int numTrees(int n) {
43+
int[] dp = new int[n + 1];
44+
dp[0] = 1;
45+
dp[1] = 1;
46+
for (int i = 2; i <= n; i++) {
47+
for (int j = 0; j < i; j++) {
48+
dp[i] += dp[j] * dp[i - j - 1];
49+
}
50+
}
51+
return dp[n];
52+
}
53+
}
54+
```
55+
56+
This implementation uses dynamic programming to compute the number of structurally unique BSTs with `n` nodes in O(n^2) time complexity.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 98\. Validate Binary Search Tree
5+
6+
Medium
7+
8+
Given the `root` of a binary tree, _determine if it is a valid binary search tree (BST)_.
9+
10+
A **valid BST** is defined as follows:
11+
12+
* The left subtree of a node contains only nodes with keys **less than** the node's key.
13+
* The right subtree of a node contains only nodes with keys **greater than** the node's key.
14+
* Both the left and right subtrees must also be binary search trees.
15+
16+
**Example 1:**
17+
18+
![](https://assets.leetcode.com/uploads/2020/12/01/tree1.jpg)
19+
20+
**Input:** root = [2,1,3]
21+
22+
**Output:** true
23+
24+
**Example 2:**
25+
26+
![](https://assets.leetcode.com/uploads/2020/12/01/tree2.jpg)
27+
28+
**Input:** root = [5,1,4,null,null,3,6]
29+
30+
**Output:** false
31+
32+
**Explanation:** The root node's value is 5 but its right child's value is 4.
33+
34+
**Constraints:**
35+
36+
* The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.
37+
* <code>-2<sup>31</sup> <= Node.val <= 2<sup>31</sup> - 1</code>
38+
39+
To solve the "Validate Binary Search Tree" problem in Java with the Solution class, follow these steps:
40+
41+
1. Define a method `isValidBST` in the `Solution` class that takes the root of a binary tree as input and returns true if the tree is a valid binary search tree (BST), and false otherwise.
42+
2. Implement a recursive approach to validate if the given binary tree is a valid BST:
43+
- Define a helper method `isValidBSTHelper` that takes the root node, a lower bound, and an upper bound as input parameters.
44+
- In the `isValidBSTHelper` method, recursively traverse the binary tree nodes.
45+
- At each node, check if its value is within the specified bounds (lower bound and upper bound) for a valid BST.
46+
- If the node's value violates the BST property, return false.
47+
- Otherwise, recursively validate the left and right subtrees by updating the bounds accordingly.
48+
- If both the left and right subtrees are valid BSTs, return true.
49+
3. Call the `isValidBSTHelper` method with the root node and appropriate initial bounds to start the validation process.
50+
51+
Here's the implementation of the `isValidBST` method in Java:
52+
53+
```java
54+
class Solution {
55+
public boolean isValidBST(TreeNode root) {
56+
return isValidBSTHelper(root, null, null);
57+
}
58+
59+
private boolean isValidBSTHelper(TreeNode node, Integer lower, Integer upper) {
60+
if (node == null) {
61+
return true;
62+
}
63+
64+
int val = node.val;
65+
if ((lower != null && val <= lower) || (upper != null && val >= upper)) {
66+
return false;
67+
}
68+
69+
return isValidBSTHelper(node.left, lower, val) && isValidBSTHelper(node.right, val, upper);
70+
}
71+
}
72+
```
73+
74+
This implementation recursively validates whether the given binary tree is a valid BST in O(n) time complexity, where n is the number of nodes in the tree.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 101\. Symmetric Tree
5+
6+
Easy
7+
8+
Given the `root` of a binary tree, _check whether it is a mirror of itself_ (i.e., symmetric around its center).
9+
10+
**Example 1:**
11+
12+
![](https://assets.leetcode.com/uploads/2021/02/19/symtree1.jpg)
13+
14+
**Input:** root = [1,2,2,3,4,4,3]
15+
16+
**Output:** true
17+
18+
**Example 2:**
19+
20+
![](https://assets.leetcode.com/uploads/2021/02/19/symtree2.jpg)
21+
22+
**Input:** root = [1,2,2,null,3,null,3]
23+
24+
**Output:** false
25+
26+
**Constraints:**
27+
28+
* The number of nodes in the tree is in the range `[1, 1000]`.
29+
* `-100 <= Node.val <= 100`
30+
31+
**Follow up:** Could you solve it both recursively and iteratively?
32+
33+
To solve the "Symmetric Tree" problem in Java with the Solution class, follow these steps:
34+
35+
1. Define a method `isSymmetric` in the `Solution` class that takes the root of a binary tree as input and returns true if the tree is symmetric, and false otherwise.
36+
2. Implement a recursive approach to check if the given binary tree is symmetric:
37+
- Define a helper method `isMirror` that takes two tree nodes as input parameters.
38+
- In the `isMirror` method, recursively compare the left and right subtrees of the given nodes.
39+
- At each step, check if the values of the corresponding nodes are equal and if the left subtree of one node is a mirror image of the right subtree of the other node.
40+
- If both conditions are satisfied for all corresponding nodes, return true; otherwise, return false.
41+
3. Call the `isMirror` method with the root's left and right children to check if the entire tree is symmetric.
42+
43+
Here's the implementation of the `isSymmetric` method in Java:
44+
45+
```java
46+
class Solution {
47+
public boolean isSymmetric(TreeNode root) {
48+
if (root == null) {
49+
return true;
50+
}
51+
return isMirror(root.left, root.right);
52+
}
53+
54+
private boolean isMirror(TreeNode left, TreeNode right) {
55+
if (left == null && right == null) {
56+
return true;
57+
}
58+
if (left == null || right == null) {
59+
return false;
60+
}
61+
return (left.val == right.val) && isMirror(left.left, right.right) && isMirror(left.right, right.left);
62+
}
63+
}
64+
```
65+
66+
This implementation recursively checks whether the given binary tree is symmetric around its center in O(n) time complexity, where n is the number of nodes in the tree.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 102\. Binary Tree Level Order Traversal
5+
6+
Medium
7+
8+
Given the `root` of a binary tree, return _the level order traversal of its nodes' values_. (i.e., from left to right, level by level).
9+
10+
**Example 1:**
11+
12+
![](https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg)
13+
14+
**Input:** root = [3,9,20,null,null,15,7]
15+
16+
**Output:** [[3],[9,20],[15,7]]
17+
18+
**Example 2:**
19+
20+
**Input:** root = [1]
21+
22+
**Output:** [[1]]
23+
24+
**Example 3:**
25+
26+
**Input:** root = []
27+
28+
**Output:** []
29+
30+
**Constraints:**
31+
32+
* The number of nodes in the tree is in the range `[0, 2000]`.
33+
* `-1000 <= Node.val <= 1000`
34+
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+
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.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 104\. Maximum Depth of Binary Tree
5+
6+
Easy
7+
8+
Given the `root` of a binary tree, return _its maximum depth_.
9+
10+
A binary tree's **maximum depth** is the number of nodes along the longest path from the root node down to the farthest leaf node.
11+
12+
**Example 1:**
13+
14+
![](https://assets.leetcode.com/uploads/2020/11/26/tmp-tree.jpg)
15+
16+
**Input:** root = [3,9,20,null,null,15,7]
17+
18+
**Output:** 3
19+
20+
**Example 2:**
21+
22+
**Input:** root = [1,null,2]
23+
24+
**Output:** 2
25+
26+
**Example 3:**
27+
28+
**Input:** root = []
29+
30+
**Output:** 0
31+
32+
**Example 4:**
33+
34+
**Input:** root = [0]
35+
36+
**Output:** 1
37+
38+
**Constraints:**
39+
40+
* The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.
41+
* `-100 <= Node.val <= 100`
42+
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
58+
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;
78+
}
79+
}
80+
}
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.

0 commit comments

Comments
 (0)