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]]
Train of thought: With two fork tree horizontal sequence problem-solving idea is similar, get the horizontal order result, then dual number chain list inversion can. ‘
The code is as follows:
/** * Definition for a binary tree node. * public class TreeNode {* int val, * TreeNode left, * TreeNode right; * TreeNode (int x) {val = x;} *} */public class Solution {list<list<integer>> List = new arraylist<list<integer>> (); Public list<list<integer>> Zigzaglevelorder (TreeNode root) {DFS (0,root); Exchange order every 1 lines for (int i = 1; i < list.size (); i = i+2) {list<integer> Al = List.get (i); int len = Al.size (); Reverse exchange for (int j = 0; J + J < Len-1; J + +) {int k = Al.get (j); Al.set (J, Al.get (Len-1-j)); Al.set (Len-1-j, k); }} return list; }/** * Sequence traversal, add list * @param the depth of the DEP tree based on depth * @param root root node */private void Dfs (int dep,treenode roo T) {if (root = null) {return; } list<integer> al;//Get Al value if (list.size () > Dep) {al = List.get (DEP) as appropriate; }else{ Al = new arraylist<integer> (); List.add (AL); } dfs (Dep+1,root.left); Al.add (Root.val); DFS (Dep+1,root.right); }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 103.Binary tree Zigzag Level order traversal (binary tree Z-shape horizontal order) thinking and method of solving problems