-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path103.二叉树的锯齿形层序遍历.java
79 lines (69 loc) · 1.8 KB
/
103.二叉树的锯齿形层序遍历.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
* @lc app=leetcode.cn id=103 lang=java
*
* [103] 二叉树的锯齿形层序遍历
*/
// @lc code=start
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res=new ArrayList<>();
if(root==null){
return res;
}
Queue<TreeNode> q=new LinkedList<>();
q.offer(root);
int level=0;
while(!q.isEmpty()){
int size=q.size();
LinkedList<Integer> l=new LinkedList<>();
for(int i=0;i<size;i++){
TreeNode node=q.poll();
if(level%2==0){
l.add(node.val);
}else{
l.addFirst(node.val);
}
if(node.left!=null){
q.offer(node.left);
}
if(node.right!=null){
q.offer(node.right);
}
}
res.add(l);
level++;
}
return res;
}
}
// @lc code=end