Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Create 0103-binary-tree-zigzag-level-order-traversal.java #3427

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions java/0103-binary-tree-zigzag-level-order-traversal.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
class Solution {
boolean reverse = false; // flag to detrmine the direction left or right
List<List<Integer>> sol = new ArrayList<List<Integer>>();
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
if(root == null){return sol;}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while( !queue.isEmpty()){
List<Integer> temp = new ArrayList<Integer>();
int size =queue.size();
for(int i=0; i < size; i++){
TreeNode node = queue.poll();
temp.add(node.val);
if(node.left != null){
queue.add(node.left);
}
if(node.right != null){
queue.add(node.right);
}
}
if(reverse){
Collections.reverse(temp);
}
reverse = !reverse;
sol.add(temp);
}
return sol;
}

}