AcWing 45. 之字形打印二叉树
原题链接
中等
作者:
Zh1995
,
2019-08-12 15:15:05
,
所有人可见
,
阅读 729
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public void reverse(LinkedList<Integer> list)
{
for(int i=0;i<list.size()/2;i++)
{
int temp=list.get(i);
list.set(i, list.get(list.size()-1-i));
list.set(list.size()-1-i, temp);
}
}
public List<List<Integer>> printFromTopToBottom(TreeNode root) {
List<List<Integer>> arr=new ArrayList<List<Integer>>();
if(root==null)
return arr;
LinkedList<Integer> list=new LinkedList<Integer>();
LinkedList<TreeNode> q=new LinkedList<TreeNode>();
q.add(root);
TreeNode last=root;
boolean flag=false;
int level=1;
while(!q.isEmpty())
{
TreeNode node=q.poll();
list.add(node.val);
if(last==node)
{
flag=true;
if(level++%2==0)//相对于上一题加上偶数行的逆置即可
reverse(list);
arr.add(list);
list=new LinkedList<Integer>();
}
if(node.left!=null)
q.add(node.left);
if(node.right!=null)
q.add(node.right);
if(flag)
{
last=q.peekLast();
flag=false;
}
}
return arr;
}
}