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 {3,9,20,#,#,15,7}
,
3 / 9 / 7
Return its zigzag level order traversal as:
[ 3], [20,9], [15,7]]
Problem Solving Ideas:
Add a reverse statement directly to the title and the Java implementation is as follows:
Public list<list<integer>> Zigzaglevelorder (TreeNode root) { list<list<integer>> List = New Arraylist<list<integer>> (); if (root = null) return List; queue<treenode> queue = new linkedlist<treenode> (); Queue.add (root); while (Queue.size ()! = 0) {list< Integer> alist = new arraylist<integer> (); for (TreeNode Child:queue) Alist.add (child.val); if (List.size ()%2!= 0) Collections.reverse (alist); List.add (new arraylist<integer> (alist)); queue<treenode> queue2 = Queue;queue = new linkedlist<treenode> (); for (TreeNode child:queue2) {if (Child.lef T! = null) Queue.add (child.left); if (child.right! = null) Queue.add (child.right);}} return list; }
Java for Leetcode 103 Binary Tree Zigzag level Order traversal