Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Created August 28, 2017 02:22
Show Gist options
  • Save cixuuz/53f519a7a066dd3bfd245b8f21a99070 to your computer and use it in GitHub Desktop.
Save cixuuz/53f519a7a066dd3bfd245b8f21a99070 to your computer and use it in GitHub Desktop.
[103. Binary Tree Zigzag Level Order Traversal] #leetcode
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
Deque<TreeNode> deque = new LinkedList<>();
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (root == null) return res;
deque.add(root);
while ( !deque.isEmpty() ) {
List<Integer> current = new LinkedList<>();
int m = deque.size();
for (int i = 0; i < m; i++) {
TreeNode node = deque.removeFirst();
if ( res.size() % 2 == 0) {
// left to right
current.add(node.val);
} else {
// right to left
current.add(0, node.val);
}
if (node.left != null) deque.add(node.left);
if (node.right != null) deque.add(node.right);
}
res.add(current);
}
return res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment