Title:
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]]
Test Instructions:
Given a binary tree, return the ' Z ' zigzag of the node of the tree (i.e. the starting order is first left and right, the next layer is in the order of first right and left, so alternately)
Like what
Given a binary tree {3,9,20,#,#,15,7} ,
3 / 9 / 7
Return the ' Z ' zigzag of this tree:
[ 3], [20,9], [15,7]]
Algorithm Analysis:
Using the result of the title "Binary Tree level Order traversal", the odd elements in the ArrayList are reversed. Less difficult, directly on the code
AC Code:
<span style= "Font-family:microsoft yahei;font-size:12px;" >public class Solution {public arraylist<arraylist<integer>> zigzaglevelorder (TreeNode root) { arraylist<arraylist<integer>> list = new arraylist<arraylist<integer>> (); if (root = null) return list; List = Levelorder (root); for (int i=1;i<list.size (); i+=2) {Reverse (List.get (i)); }return list; } private static void reverse (arraylist<integer> temlist) {int tem=0; int temsize=0; if (Temlist.size ()%2==0) temsize=temlist.size ()/2-1; else Temsize=temlist.size ()/2; for (int i=0;i<=temsize;i++) {tem=temlist.get (i); Temlist.set (i, Temlist.get (Temlist.size () -1-i)); Temlist.set ( Temlist.size () -1-i, TEM); }} public static arraylist<arraylist<integer>> Levelorder (TreeNode root) {Arraylist<arraylist<integer>> res = new arraylist<arraylist<integer>> (); if (root = null) {return res; } arraylist<integer> tmp = new arraylist<integer> (); queue<treenode> queue = new linkedlist<treenode> (); Queue.offer (root); int num; Boolean reverse = false; while (!queue.isempty ()) {num = Queue.size (); Each time through this determines the final number of teams tmp.clear (); for (int i = 0; i < num; i++)//1 fathers in the queue, two children, 2 fathers, 4 children, 4 fathers, 8 children {TreeNode node = Queue.po ll (); Tmp.add (Node.val); if (node.left! = null) Queue.offer (node.left); if (node.right! = null) Queue.offer (node.right); } res.add (New Arraylist<integer> (TMP)); } return res; }}</span>
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Binary Tree Zigzag level Order traversal