Binary Tree Zigzag Level Order Traversal
题目
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]
]
分析
- totally the same question as Binary Tree Level Order Traversal, except that due to zigzag level order,
Collections.reverse
is needed here
图解
解题
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) return result;
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
Boolean left_to_right = true;
while(!q.isEmpty()) {
int levelNodeNum = q.size();
List<Integer> currLevel = new ArrayList<>();
for(int i = 0; i < levelNodeNum; i++) {
TreeNode currNode = q.poll();
currLevel.add(currNode.val);
if (currNode.left != null)
q.add(currNode.left);
if (currNode.right != null)
q.add(currNode.right);
}
if(!left_to_right) Collections.reverse(currLevel);
result.add(currLevel);
left_to_right = !left_to_right;
}
return result;
}
}