Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 68d5bbc

Browse files
add q103
1 parent fb85dd5 commit 68d5bbc

File tree

4 files changed

+57
-0
lines changed

4 files changed

+57
-0
lines changed

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,7 @@
119119

120120
- [q94_二叉树的中序遍历](/src/树的遍历/q94_二叉树的中序遍历)
121121
- [q102_二叉树的层次遍历](/src/树的遍历/q102_二叉树的层次遍历)
122+
- [q103_二叉树的锯齿形层序遍历](/src/树的遍历/q103_二叉树的锯齿形层序遍历)
122123
- [q110_平衡二叉树](/src/树的遍历/q110_平衡二叉树)
123124
- [q144_二叉树的前序遍历](/src/树的遍历/q144_二叉树的前序遍历)
124125
- [q145_二叉树的后序遍历](/src/树的遍历/q145_二叉树的后序遍历)

‎README_EN.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,7 @@
119119

120120
- [Question 94 : Binary Tree Inorder Traversal](/src/树的遍历/q94_二叉树的中序遍历)
121121
- [Question 102 : Binary Tree Level Order Traversal](/src/树的遍历/q102_二叉树的层次遍历)
122+
- [Question 103 : Binary Tree Zigzag Level Order Traversal](/src/树的遍历/q103_二叉树的锯齿形层序遍历)
122123
- [Question 110 : Balanced Binary Tree](/src/树的遍历/q110_平衡二叉树)
123124
- [Question 144 : Binary Tree Preorder Traversal](/src/树的遍历/q144_二叉树的前序遍历)
124125
- [Question 145 : Binary Tree Postorder Traversal](/src/树的遍历/q145_二叉树的后序遍历)
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package 树的遍历.q103_二叉树的锯齿形层序遍历;
2+
3+
import java.util.ArrayList;
4+
import java.util.LinkedList;
5+
import java.util.List;
6+
import java.util.Queue;
7+
8+
/**
9+
* 和层序遍历相同,额外加一个标记控制插入队列的位置
10+
*/
11+
public class Solution {
12+
13+
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
14+
List<List<Integer>> ans = new ArrayList<>();
15+
if (root == null) {
16+
return ans;
17+
}
18+
Queue<TreeNode> queue = new LinkedList<>();
19+
queue.add(root);
20+
boolean flag = true;
21+
while (!queue.isEmpty()) {
22+
List<Integer> list = new ArrayList<>();
23+
int size = queue.size();
24+
while (size > 0) {
25+
TreeNode tn = queue.poll();
26+
if (flag) {
27+
list.add(tn.val);
28+
} else {
29+
list.add(0, tn.val);
30+
}
31+
if (tn.left != null) {
32+
queue.add(tn.left);
33+
}
34+
if (tn.right != null) {
35+
queue.add(tn.right);
36+
}
37+
size--;
38+
}
39+
flag = !flag;
40+
ans.add(list);
41+
}
42+
return ans;
43+
}
44+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package 树的遍历.q103_二叉树的锯齿形层序遍历;
2+
3+
public class TreeNode {
4+
int val;
5+
TreeNode left;
6+
TreeNode right;
7+
8+
TreeNode(int x) {
9+
val = x;
10+
}
11+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /