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: 3 / \ 9 20 / \ 15 7 return its zigzag level order traversal as:
|
3 / \ 9 20 / \ 15 7 For example, the zig zag level order output of the tree above is: 3 20 9 15 7 This question is a variation of the question Printing a Binary Tree in Level Order. Hint: Solution: You pop from stack currentLevel and print the node's value. Whenever the current level's order is from left->right, you push the node's left child, then its right child to stack nextLevel. Remember a Stack is a Last In First OUT (LIFO) structure, so the next time when nodes are popped off nextLevel, it will be in the reverse order. On the other hand, when the current level's order is from right->left, you would push the node's right child first, then its left child. Finally, don't forget to swap those two stacks at the end of each level (ie, when currentLevel is empty).
|
|
|
|
uses 2 stacks for alternate levels /* * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } / public class Solution {
} |
|
|
|