二叉树的锯齿形层次遍历
题目
给出一棵二叉树,返回其节点值的锯齿形层次遍历(先从左往右,下一层再从右往左,层与层之间交替进行)
样例
给出一棵二叉树 {3,9,20,#,#,15,7},
返回其锯齿形的层次遍历为:
题解
隔行对层序遍历结果进行反转。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: A list of lists of integer include
* the zigzag level order traversal of its nodes' values
*/
public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
if (root == null)
{
return list;
}
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.add(root);
boolean reverse = false;
while (!q.isEmpty())
{
ArrayList<Integer> arr = new ArrayList<Integer>();
int n = q.size();
for (int i=0;i<n;i++)
{
TreeNode t = q.poll();
arr.add(t.val);
if (t.left != null)
{
q.add(t.left);
}
if (t.right != null)
{
q.add(t.right);
}
}
if (reverse)
{
reverse(arr);
}
reverse = !reverse;
list.add(arr);
}
return list;
}
private void reverse(ArrayList<Integer> list)
{
int start = 0;
int end = list.size()-1;
while (start < end)
{
int temp = list.get(start);
list.set(start++,list.get(end));
list.set(end--,temp);
}
}
}
Last Update 2016.9.22