ID | Title | Difficulty | |
---|---|---|---|
Loading... |
103. Binary Tree Zigzag Level Order Traversal
Medium
LeetCode
Tree, Breadth-First Search, Binary Tree
Problem
Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between).
For example: Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
Code
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) return res;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
boolean left2right = true;
while(!queue.isEmpty()){
int size = queue.size();
List<Integer> level = new ArrayList<>();
for(int i = 0; i < size; i++){
TreeNode curr = queue.poll();
if(left2right == true){
level.add(curr.val);
} else{
level.add(0, curr.val);
}
if(curr.left != null) queue.add(curr.left);
if(curr.right != null) queue.add(curr.right);
}
res.add(level);
left2right = !left2right;
}
return res;
}
}
按 <- 键看上一题!
102. Binary Tree Level Order Traversal
按 -> 键看下一题!
104. Maximum Depth of Binary Tree