Skip to content

Commit 43d8cf8

Browse files
authored
feat: add solutions for lc No.3902 (#5160)
1 parent c9e00f1 commit 43d8cf8

12 files changed

Lines changed: 896 additions & 1 deletion

File tree

Lines changed: 340 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,340 @@
1+
---
2+
comments: true
3+
difficulty: 中等
4+
edit_url: https://github.com/doocs/leetcode/edit/main/solution/3900-3999/3902.Zigzag%20Level%20Sum%20of%20Binary%20Tree/README.md
5+
---
6+
7+
<!-- problem:start -->
8+
9+
# [3902. Zigzag Level Sum of Binary Tree 🔒](https://leetcode.cn/problems/zigzag-level-sum-of-binary-tree)
10+
11+
[English Version](/solution/3900-3999/3902.Zigzag%20Level%20Sum%20of%20Binary%20Tree/README_EN.md)
12+
13+
## 题目描述
14+
15+
<!-- description:start -->
16+
17+
<p>You are given the <code>root</code> of a <strong>binary tree</strong>.</p>
18+
19+
<p>Traverse the tree level by level using a zigzag pattern:</p>
20+
21+
<ul>
22+
<li>At <strong>odd</strong>-numbered levels (1-indexed), traverse nodes from <strong>left to right</strong>.</li>
23+
<li>At <strong>even</strong>-numbered levels, traverse nodes from <strong>right to left</strong>.</li>
24+
</ul>
25+
26+
<p>While traversing a level in the specified direction, process nodes in order and <strong>stop</strong> immediately before the first node that violates the condition:</p>
27+
28+
<ul>
29+
<li>At <strong>odd</strong> levels: the node does not have a <strong>left</strong> child.</li>
30+
<li>At <strong>even</strong> levels: the node does not have a <strong>right</strong> child.</li>
31+
</ul>
32+
33+
<p>Only the nodes processed before this stopping condition contribute to the level sum.</p>
34+
35+
<p>Return an integer array <code>ans</code> where <code>ans[i]</code> is the <strong>sum</strong> of the node values that are processed at level <code>i + 1</code>.</p>
36+
37+
<p>&nbsp;</p>
38+
<p><strong class="example">Example 1:</strong></p>
39+
40+
<div class="example-block">
41+
<p><strong>Input:</strong> <span class="example-io">root = [5,2,8,1,null,9,6]</span></p>
42+
43+
<p><strong>Output:</strong> <span class="example-io">[5,8,0]</span></p>
44+
45+
<p><strong>Explanation:</strong></p>
46+
47+
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3900-3999/3902.Zigzag%20Level%20Sum%20of%20Binary%20Tree/images/screenshot-2026-04-13-at-22054am.png" style="height: 240px; width: 300px;" />​​​​​​​</p>
48+
49+
<ul>
50+
<li>At level 1, nodes are processed left to right. Node 5 is included, thus <code>ans[0] = 5</code>.</li>
51+
<li>At level 2, nodes are processed right to left. Node 8 is included, but node 2 lacks a right child, so processing stops, thus <code>ans[1] = 8</code>.</li>
52+
<li>At level 3, nodes are processed left to right. The first node 1 lacks a left child, so no nodes are included, and <code>ans[2] = 0</code>.</li>
53+
<li>Thus, <code>ans = [5, 8, 0]</code>.</li>
54+
</ul>
55+
</div>
56+
57+
<p><strong class="example">Example 2:</strong></p>
58+
59+
<div class="example-block">
60+
<p><strong>Input:</strong> <span class="example-io">root = [1,2,3,4,5,null,7]</span></p>
61+
62+
<p><strong>Output:</strong> <span class="example-io">[1,5,0]</span></p>
63+
64+
<p><strong>Explanation:</strong></p>
65+
66+
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3900-3999/3902.Zigzag%20Level%20Sum%20of%20Binary%20Tree/images/screenshot-2026-04-13-at-22232am.png" style="height: 254px; width: 300px;" /></p>
67+
68+
<ul>
69+
<li>At level 1, nodes are processed left to right. Node 1 is included, thus <code>ans[0] = 1</code>.</li>
70+
<li>At level 2, nodes are processed right to left. Nodes 3 and 2 are included since both have right children, thus <code>ans[1] = 3 + 2 = 5</code>.</li>
71+
<li>At level 3, nodes are processed left to right. The first node 4 lacks a left child, so no nodes are included, and <code>ans[2] = 0</code>.</li>
72+
<li>Thus, <code>ans = [1, 5, 0]</code>.</li>
73+
</ul>
74+
</div>
75+
76+
<p>&nbsp;</p>
77+
<p><strong>Constraints:</strong></p>
78+
79+
<ul>
80+
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
81+
<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>
82+
</ul>
83+
84+
<!-- description:end -->
85+
86+
## 解法
87+
88+
<!-- solution:start -->
89+
90+
### 方法一:BFS
91+
92+
我们使用一个队列 $q$ 来进行层序遍历,定义一个布尔变量 $\textit{left}$ 来表示当前层的遍历方向。对于每一层,我们先将下一层的节点加入队列 $nq$ 中,然后根据 $\textit{left}$ 的值来计算当前层的节点值之和 $s$,并将 $s$ 添加到答案数组中。最后,更新 $\textit{left}$ 的值,并将 $nq$ 赋值给 $q$ 以继续下一层的遍历。
93+
94+
时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树中节点的数量。
95+
96+
<!-- tabs:start -->
97+
98+
#### Python3
99+
100+
```python
101+
# Definition for a binary tree node.
102+
# class TreeNode:
103+
# def __init__(self, val=0, left=None, right=None):
104+
# self.val = val
105+
# self.left = left
106+
# self.right = right
107+
class Solution:
108+
def zigzagLevelSum(self, root: TreeNode | None) -> list[int]:
109+
q = [root]
110+
ans = []
111+
left = True
112+
while q:
113+
nq = []
114+
for node in q:
115+
if node.left:
116+
nq.append(node.left)
117+
if node.right:
118+
nq.append(node.right)
119+
m = len(q)
120+
s = 0
121+
for i in range(m):
122+
node = q[i] if left else q[m - i - 1]
123+
child = node.left if left else node.right
124+
if not child:
125+
break
126+
s += node.val
127+
ans.append(s)
128+
left = not left
129+
q = nq
130+
return ans
131+
```
132+
133+
#### Java
134+
135+
```java
136+
/**
137+
* Definition for a binary tree node.
138+
* public class TreeNode {
139+
* int val;
140+
* TreeNode left;
141+
* TreeNode right;
142+
* TreeNode() {}
143+
* TreeNode(int val) { this.val = val; }
144+
* TreeNode(int val, TreeNode left, TreeNode right) {
145+
* this.val = val;
146+
* this.left = left;
147+
* this.right = right;
148+
* }
149+
* }
150+
*/
151+
class Solution {
152+
public List<Long> zigzagLevelSum(TreeNode root) {
153+
List<Long> ans = new ArrayList<>();
154+
List<TreeNode> q = new ArrayList<>();
155+
q.add(root);
156+
boolean left = true;
157+
while (!q.isEmpty()) {
158+
List<TreeNode> nq = new ArrayList<>();
159+
for (TreeNode node : q) {
160+
if (node.left != null) {
161+
nq.add(node.left);
162+
}
163+
if (node.right != null) {
164+
nq.add(node.right);
165+
}
166+
}
167+
int m = q.size();
168+
long s = 0;
169+
for (int i = 0; i < m; i++) {
170+
TreeNode node = left ? q.get(i) : q.get(m - i - 1);
171+
TreeNode child = left ? node.left : node.right;
172+
if (child == null) {
173+
break;
174+
}
175+
s += node.val;
176+
}
177+
ans.add(s);
178+
left = !left;
179+
q = nq;
180+
}
181+
return ans;
182+
}
183+
}
184+
```
185+
186+
#### C++
187+
188+
```cpp
189+
/**
190+
* Definition for a binary tree node.
191+
* struct TreeNode {
192+
* int val;
193+
* TreeNode *left;
194+
* TreeNode *right;
195+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
196+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
197+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
198+
* };
199+
*/
200+
class Solution {
201+
public:
202+
vector<long long> zigzagLevelSum(TreeNode* root) {
203+
vector<long long> ans;
204+
vector<TreeNode*> q = {root};
205+
bool left = true;
206+
while (!q.empty()) {
207+
vector<TreeNode*> nq;
208+
for (TreeNode* node : q) {
209+
if (node->left != nullptr) {
210+
nq.push_back(node->left);
211+
}
212+
if (node->right != nullptr) {
213+
nq.push_back(node->right);
214+
}
215+
}
216+
int m = q.size();
217+
long long s = 0;
218+
for (int i = 0; i < m; i++) {
219+
TreeNode* node = left ? q[i] : q[m - i - 1];
220+
TreeNode* child = left ? node->left : node->right;
221+
if (child == nullptr) {
222+
break;
223+
}
224+
s += node->val;
225+
}
226+
ans.push_back(s);
227+
left = !left;
228+
q = nq;
229+
}
230+
return ans;
231+
}
232+
};
233+
```
234+
235+
#### Go
236+
237+
```go
238+
/**
239+
* Definition for a binary tree node.
240+
* type TreeNode struct {
241+
* Val int
242+
* Left *TreeNode
243+
* Right *TreeNode
244+
* }
245+
*/
246+
func zigzagLevelSum(root *TreeNode) []int64 {
247+
ans := []int64{}
248+
q := []*TreeNode{root}
249+
left := true
250+
for len(q) > 0 {
251+
nq := []*TreeNode{}
252+
for _, node := range q {
253+
if node.Left != nil {
254+
nq = append(nq, node.Left)
255+
}
256+
if node.Right != nil {
257+
nq = append(nq, node.Right)
258+
}
259+
}
260+
m := len(q)
261+
var s int64 = 0
262+
for i := 0; i < m; i++ {
263+
var node *TreeNode
264+
if left {
265+
node = q[i]
266+
} else {
267+
node = q[m-i-1]
268+
}
269+
var child *TreeNode
270+
if left {
271+
child = node.Left
272+
} else {
273+
child = node.Right
274+
}
275+
if child == nil {
276+
break
277+
}
278+
s += int64(node.Val)
279+
}
280+
ans = append(ans, s)
281+
left = !left
282+
q = nq
283+
}
284+
return ans
285+
}
286+
```
287+
288+
#### TypeScript
289+
290+
```ts
291+
/**
292+
* Definition for a binary tree node.
293+
* class TreeNode {
294+
* val: number
295+
* left: TreeNode | null
296+
* right: TreeNode | null
297+
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
298+
* this.val = (val===undefined ? 0 : val)
299+
* this.left = (left===undefined ? null : left)
300+
* this.right = (right===undefined ? null : right)
301+
* }
302+
* }
303+
*/
304+
function zigzagLevelSum(root: TreeNode | null): number[] {
305+
let q: TreeNode[] = [root];
306+
const ans: number[] = [];
307+
let left = true;
308+
while (q.length > 0) {
309+
const nq: TreeNode[] = [];
310+
for (const { left, right } of q) {
311+
if (left !== null) {
312+
nq.push(left);
313+
}
314+
if (right !== null) {
315+
nq.push(right);
316+
}
317+
}
318+
const m = q.length;
319+
let s = 0;
320+
for (let i = 0; i < m; i++) {
321+
const node = left ? q[i] : q[m - i - 1];
322+
const child = left ? node.left : node.right;
323+
if (child === null) {
324+
break;
325+
}
326+
s += node.val;
327+
}
328+
ans.push(s);
329+
left = !left;
330+
q = nq;
331+
}
332+
return ans;
333+
}
334+
```
335+
336+
<!-- tabs:end -->
337+
338+
<!-- solution:end -->
339+
340+
<!-- problem:end -->

0 commit comments

Comments
 (0)