Skip to content

Commit 8d26911

Browse files
Added 0116
1 parent f1ac4d9 commit 8d26911

File tree

1 file changed

+76
-52
lines changed

1 file changed

+76
-52
lines changed

dsa-solutions/lc-solutions/0100-0199/0113-path-sum-2.md

Lines changed: 76 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,52 @@
11
---
2-
id: 113-path-sum-2
3-
title: Path Sum 2
4-
sidebar_label: 0113-Path Sum 2
2+
id: 116-populating-next-right-pointers-in-each-node
3+
title: Populating Next Right Pointers in Each Node
4+
sidebar_label: 0116-Populating Next Right Pointers in Each Node
55
tags:
66
- Java
77
- Python
88
- C++
9-
description: "Find all root-to-leaf paths in a binary tree where the sum of the node values equals a given number."
9+
description: "Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL."
1010
---
1111

1212
## Problem Description
1313

14-
Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of node values, and paths are represented as lists of node values.
14+
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
15+
16+
Initially, all next pointers are set to NULL.
1517

1618
### Examples
1719

1820
**Example 1:**
1921

20-
![LeetCode Problem - Binary Tree](https://assets.leetcode.com/uploads/2021/01/18/pathsumii1.jpg)
22+
![LeetCode Problem - Binary Tree](https://assets.leetcode.com/uploads/2019/02/14/116_sample.png)
2123
```
22-
Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
23-
Output: [[5,4,11,2],[5,8,4,5]]
24+
Input: root = [1,2,3,4,5,6,7]
25+
Output: [1,#,2,3,#,4,5,6,7,#]
2426
```
2527

26-
**Example 1:**
28+
**Example 2:**
2729

28-
![LeetCode Problem - Binary Tree](https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg)
2930
```
30-
Input: root = [1,2,3], targetSum = 5
31+
Input: root = []
3132
Output: []
3233
```
3334

3435
### Constraints
3536

36-
- The number of nodes in the tree is in the range [0, 105].
37+
- The number of nodes in the tree is in the range [0, 212 - 1].
3738
- $-1000 <= Node.val <= 1000$
38-
- $-1000 <= targetSum <= 1000$
39+
3940
---
4041

4142
## Solution for Binary Tree Problem
4243

4344
### Intuition And Approach
4445

45-
To find all root-to-leaf paths where the sum equals targetSum, we can use Depth-First Search (DFS). We'll traverse the tree and keep track of the current path and its sum. When a leaf node is reached, we check if the current path's sum equals targetSum. If it does, we add the path to our result list.
46+
To populate each next pointer to point to its next right node in a perfect binary tree, we can perform a level order traversal and connect nodes at the same level.
4647

4748
<Tabs>
48-
<tabItem value="Recursive" label="Recursive">
49+
<tabItem value="Linear" label="Linear">
4950

5051

5152
#### Code in Different Languages
@@ -54,57 +55,80 @@ To find all root-to-leaf paths where the sum equals targetSum, we can use Depth-
5455
<TabItem value="Java" label="Java" default>
5556
<SolutionAuthor name="@Vipullakum007"/>
5657
```java
57-
private void dfs(TreeNode node, int sum, List<Integer> path, List<List<Integer>> result) {
58-
if (node == null) return;
59-
path.add(node.val);
60-
if (node.left == null && node.right == null && node.val == sum) {
61-
result.add(new ArrayList<>(path));
62-
} else {
63-
dfs(node.left, sum - node.val, path, result);
64-
dfs(node.right, sum - node.val, path, result);
58+
class Solution {
59+
public Node connect(Node root) {
60+
if (root == null) return null;
61+
Queue<Node> queue = new LinkedList<>();
62+
queue.offer(root);
63+
while (!queue.isEmpty()) {
64+
int levelSize = queue.size();
65+
Node prev = null;
66+
for (int i = 0; i < levelSize; i++) {
67+
Node curr = queue.poll();
68+
if (prev != null) {
69+
prev.next = curr;
70+
}
71+
if (curr.left != null) queue.offer(curr.left);
72+
if (curr.right != null) queue.offer(curr.right);
73+
prev = curr;
74+
}
75+
}
76+
return root;
6577
}
66-
path.remove(path.size() - 1);
6778
}
6879
```
6980

7081
</TabItem>
7182
<TabItem value="Python" label="Python">
7283
<SolutionAuthor name="@Vipullakum007"/>
7384
```python
74-
class Solution:
75-
def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]:
76-
def dfs(node, current_path, current_sum):
77-
if not node:
78-
return
79-
current_path.append(node.val)
80-
current_sum += node.val
81-
if not node.left and not node.right and current_sum == targetSum:
82-
result.append(list(current_path))
83-
else:
84-
dfs(node.left, current_path, current_sum)
85-
dfs(node.right, current_path, current_sum)
86-
current_path.pop()
87-
88-
result = []
89-
dfs(root, [], 0)
90-
return result
85+
class Solution:
86+
def connect(self, root: 'Node') -> 'Node':
87+
if not root:
88+
return None
89+
queue = collections.deque([root])
90+
while queue:
91+
level_size = len(queue)
92+
prev = None
93+
for _ in range(level_size):
94+
node = queue.popleft()
95+
if prev:
96+
prev.next = node
97+
if node.left:
98+
queue.append(node.left)
99+
if node.right:
100+
queue.append(node.right)
101+
prev = node
102+
return root
91103
```
92104

93105
</TabItem>
94106
<TabItem value="C++" label="C++">
95107
<SolutionAuthor name="@Vipullakum007"/>
96108
```cpp
97-
void dfs(TreeNode* node, int sum, vector<int>& path, vector<vector<int>>& result) {
98-
if (!node) return;
99-
path.push_back(node->val);
100-
if (!node->left && !node->right && node->val == sum) {
101-
result.push_back(path);
102-
} else {
103-
dfs(node->left, sum - node->val, path, result);
104-
dfs(node->right, sum - node->val, path, result);
109+
class Solution {
110+
public:
111+
Node* connect(Node* root) {
112+
if (!root) return nullptr;
113+
queue<Node*> q;
114+
q.push(root);
115+
while (!q.empty()) {
116+
int levelSize = q.size();
117+
Node* prev = nullptr;
118+
for (int i = 0; i < levelSize; ++i) {
119+
Node* node = q.front();
120+
q.pop();
121+
if (prev) {
122+
prev->next = node;
123+
}
124+
if (node->left) q.push(node->left);
125+
if (node->right) q.push(node->right);
126+
prev = node;
127+
}
128+
}
129+
return root;
105130
}
106-
path.pop_back();
107-
}
131+
};
108132
```
109133

110134
</TabItem>
@@ -113,7 +137,7 @@ To find all root-to-leaf paths where the sum equals targetSum, we can use Depth-
113137
#### Complexity Analysis
114138

115139
- Time Complexity: $O(n)$ where n is the number of nodes in the binary tree.
116-
- Space Complexity: $O(h)$ where h is the height of the binary tree.
140+
- Space Complexity: $O(m)$ where m is the maximum number of nodes at any level in the binary tree. In the worst case, the queue can contain all nodes at the last level, which is at most $2^{h-1}$ where h is the height of the tree.
117141

118142
</tabItem>
119143
</Tabs>

0 commit comments

Comments
 (0)