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]]
Confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
OJ ' s Binary Tree serialization:
The serialization of a binary tree follows a level order traversal, where ' # ' signifies a path terminator where no node ex Ists below.
Here's an example:
1 / 2 3 / 4 5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}" .
Test instructions: The hierarchy traverses a tree, flipping over odd layers.
Idea: or use the queue hierarchy traversal, more than one to determine whether to flip the tag on the line, there is a reference to Java is passed, so every time you want to re-declare an object, or ans inside is pointing to the same block of memory.
/** * Definition for Binary tree * public class TreeNode {* int val, * TreeNode left, * TreeNode right; TreeNode (int x) {val = x;} *} */public class Solution {public list<list<integer>> Zigzaglevelorder (Tre Enode root) {list<list<integer>> ans = new arraylist<list<integer>> (); if (root = null) return ans; queue<treenode> queue = new linkedlist<treenode> (); Queue.add (root); Boolean reverse = false; while (!queue.isempty ()) {list<integer> tmp = new arraylist<integer> (); int num = Queue.size (); for (int i = 0; i < num; i++) {TreeNode t = queue.poll (); Tmp.add (T.val); if (t.left! = null) Queue.add (t.left); if (t.right! = null) Queue.add (t.right); } if (reverse) {collections.reverse (TMP); Reverse = false; } else reverse = true; Ans.add (TMP); } return ans; }}
Leetcode Binary Tree Zigzag level Order traversal