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
Given binary tree
{3,9,20,#,#,15,7}, 3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
Use bfs to traverse level by level and reverse temp result in even rows.
/**
public class Solution {
public ArrayList> zigzagLevelOrder(TreeNode root) {
ArrayList> result = new ArrayList>();
ArrayList toVisit = new ArrayList();
if(root == null)
return result;
toVisit.add(root);
boolean flag = true;
while(!toVisit.isEmpty()){
ArrayList tmp = new ArrayList();
for(TreeNode tn : toVisit)
tmp.add(tn.val);
result.add(tmp);
// why start from the last element?
// write an example on paper then you will see.
ArrayList next = new ArrayList();
for(int i = toVisit.size()-1; i >= 0 ; i--){
TreeNode tn = toVisit.get(i);
if(flag){
if(tn.right != null) next.add(tn.right);
if(tn.left != null) next.add(tn.left);
}
else{
if(tn.left != null) next.add(tn.left);
if(tn.right != null) next.add(tn.right);
}
}
// change flag alternatively
flag = flag ? false : true;
toVisit = new ArrayList(next);
}
return result;
}
}
No comments:
Post a Comment