题目:给定一个二叉树,返回该二叉树的之字形层序遍历,(第一层从左向右,下一层从右向左,一直这样交替)
例如:
给定的二叉树是{3,9,20,15,7,#,#},使用之字遍历的结果为[[3],[20][9],[15][7]]
算法思想:为每一行建立newLIst与newLine,和行标识符flag(flag=0:倒着输入某一行,flag=1:正着输入)
根据flag将结点的值以数组的形式存入到newLine之中,之后在添加到大数组result中
将此行结点的左右孩子添加到newlist之中,为遍历下一行做准备。
代码分析 :
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
与我们常见的ArrayList<E> Rename = new ArrayList<>();不太一样,ArrayList<ArrayList<Integer>> 通俗来讲就是ArrayList 中存放ArrayList,及将(小)数组存放在(大数组)
之中。
举个例子:
ArrayList<ArrayList<Integer>> res = ArrayList<ArrayList<Integer>>();
ArrayLIst<Integer> list = new ArrayLIst<Integer>();
list.add(1);//向list添加元素1
list.add(2);
res.add(list);//将数组list添加到res当中
return res;
结果为:[[1,2]] :注意两层中括号