Copy Input: root = [3,9,20,null,null,15,7]
Output: [[3],[20,9],[15,7]]
Copy Input: root = [1]
Output: [[1]]
Copy Input: root = []
Output: []
Copy class Solution {
public List < List < Integer >> zigzagLevelOrder ( TreeNode root) {
List < List < Integer >> res = new LinkedList <>();
if (root == null ) {
return res;
}
Queue < TreeNode > q = new LinkedList <>();
q . offer (root);
// 为 true 时向右,false 时向左
boolean flag = true ;
// while 循环控制从上向下一层层遍历
while ( ! q . isEmpty ()) {
int sz = q . size ();
// 记录这一层的节点值
LinkedList < Integer > level = new LinkedList <>();
// for 循环控制每一层从左向右遍历
for ( int i = 0 ; i < sz; i ++ ) {
TreeNode cur = q . poll ();
// 实现 z 字形遍历
if (flag) {
level . addLast ( cur . val );
} else {
level . addFirst ( cur . val );
}
if ( cur . left != null )
q . offer ( cur . left );
if ( cur . right != null )
q . offer ( cur . right );
}
// 切换方向
flag = ! flag;
res . add (level);
}
return res;
}
}
Copy class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result=new ArrayList<>();
if(root==null){
return result;
}
LinkedList<TreeNode> queue=new LinkedList<TreeNode>();
queue.offer(root);
while(!queue.isEmpty()){
List<Integer> level=new ArrayList<Integer>();
int size=queue.size();
for(int i=0;i<size;i++){
TreeNode current=queue.poll();
level.add(current.val);
if(current.left!=null){
queue.offer(current.left);
}
if(current.right!=null){
queue.offer(current.right);
}
}
result.add(level);
}
for(int j = 0; j< result.size(); j++)
{
if(j%2 == 1)
{
Collections.reverse(result.get(j));
}
}
return result;
}
}