定义一个变量isFromLeft
如果isFromLeft为true,则将节点的值添加到列表的尾部
否则,添加到列表的头部?
if(isFromLeft) {
oneLevel.add(cur.val);
} else {
oneLevel.add(0 , cur.val);
}
遍历完当前层之后,移动到下一层,则从相反的方向开始访问当前层的所有节点
isFromLeft = !isFromLeft;
完整代码
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
LinkedList<List<Integer>> result = new LinkedList<>();
if(root == null) {
return result;
}
LinkedList<TreeNode> queue = new LinkedList<>();
queue.add(root);
boolean isFromLeft = true;
while(!queue.isEmpty()) {
List<Integer> oneLevel = new ArrayList<>();
int size = queue.size();
for(int i = 0; i < size; i++) {
TreeNode cur = queue.poll();
if(isFromLeft) {
oneLevel.add(cur.val);
} else {
oneLevel.add(0 , cur.val);
}
if(cur.left != null) {
queue.add(cur.left);
}
if(cur.right != null) {
queue.add(cur.right);
}
}
isFromLeft = !isFromLeft;
result.add(oneLevel);
}
return result;
}
}
|