层序遍历的变式,用双端队列来实现偶数行从左到右,奇数行从右到左(索引从0开始),代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res=new ArrayList<>();
Queue<TreeNode> queue=new LinkedList<>();
if(root!=null) queue.add(root);
while(!queue.isEmpty()){
LinkedList<Integer> tempList=new LinkedList<>();
for(int i=queue.size();i>0;i--){
TreeNode node=queue.poll();
if(res.size()%2==0) tempList.addLast(node.val);
else tempList.addFirst(node.val);
if(node.left!=null) queue.add(node.left);
if(node.right!=null) queue.add(node.right);
}
res.add(tempList);
}
return res;
}
}