You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
title: Populating Next Right Pointers in Each Node
4
+
sidebar_label: 0116-Populating Next Right Pointers in Each Node
5
5
tags:
6
6
- Java
7
7
- Python
8
8
- 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."
10
10
---
11
11
12
12
## Problem Description
13
13
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.
15
17
16
18
### Examples
17
19
18
20
**Example 1:**
19
21
20
-

22
+


29
30
```
30
-
Input: root = [1,2,3], targetSum = 5
31
+
Input: root = []
31
32
Output: []
32
33
```
33
34
34
35
### Constraints
35
36
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].
37
38
- $-1000 <= Node.val <= 1000$
38
-
- $-1000 <= targetSum <= 1000$
39
+
39
40
---
40
41
41
42
## Solution for Binary Tree Problem
42
43
43
44
### Intuition And Approach
44
45
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.
46
47
47
48
<Tabs>
48
-
<tabItemvalue="Recursive"label="Recursive">
49
+
<tabItemvalue="Linear"label="Linear">
49
50
50
51
51
52
#### Code in Different Languages
@@ -54,57 +55,80 @@ To find all root-to-leaf paths where the sum equals targetSum, we can use Depth-
54
55
<TabItemvalue="Java"label="Java"default>
55
56
<SolutionAuthorname="@Vipullakum007"/>
56
57
```java
57
-
privatevoid 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) {
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
+
classSolution:
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
91
103
```
92
104
93
105
</TabItem>
94
106
<TabItem value="C++" label="C++">
95
107
<SolutionAuthor name="@Vipullakum007"/>
96
108
```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
+
classSolution {
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;
105
130
}
106
-
path.pop_back();
107
-
}
131
+
};
108
132
```
109
133
110
134
</TabItem>
@@ -113,7 +137,7 @@ To find all root-to-leaf paths where the sum equals targetSum, we can use Depth-
113
137
#### ComplexityAnalysis
114
138
115
139
-TimeComplexity: $O(n)$ where n is the number of nodes in the binary tree.
116
-
-SpaceComplexity: $O(h)$ where h is the height of the binary tree.
140
+
-SpaceComplexity: $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.
0 commit comments