Given a binary tree and return to 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,#,#,15,7},
3
/ \
9 20
/ \
15 7
Return it zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
Sequence traversal of binary trees in this way zigzag
Solution: Through the topic requirements we can know that the current traversal layer as the base, the way to traverse is from left to right, or from right to left. Then we are traversing the process as long as the current layer to determine the traversal of the elements into the storage structure of the insertion mode can be, from left to right to insert the normal, vice versa is inserted. The rest is the normal sequence traversal.
Code:
public class Solution {public list<list<integer>> zigzaglevelorder (TreeNode root) {list<
list<integer>> result = new arraylist<list<integer>> ();
Travel (result, root, 0);
return result;
private void Travel (list<list<integer>> result, TreeNode root, int level) {if (root = null) {
Return
} if (Result.size () <= level) {list<integer> next = new linkedlist<> ();
Result.add (next);
list<integer> temp = Result.get (level);
if (level% 2 = 0) {temp.add (root.val);
} else{temp.add (0, Root.val);
Travel (result, root.left, level + 1);
Travel (result, root.right, level + 1); }
}