ð 103. äºåæ çé¯éœ¿åœ¢å±åºéå
2022幎10æ10æ¥
- algorithm
ð 103. äºåæ çé¯éœ¿åœ¢å±åºéå
éŸåºŠ: ð
é®é¢æè¿°
解æ³
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
// æè·¯ïŒ
// å±åº - åå© éå
List<List<Integer>> res = new ArrayList<>();
LinkedList<TreeNode> queue = new LinkedList<>();
if(root == null) {
return res;
}
queue.offer(root);
boolean flag = true;
while(!queue.isEmpty()) {
int len = queue.size(); // åœåå±èç¹äžªæ°
LinkedList<Integer> list = new LinkedList<>();
for(int i = 0; i < len; i ++) {
TreeNode cur = queue.poll();
if(flag) {
list.addLast(cur.val);
} else {
list.addFirst(cur.val);
}
if(cur.left != null) {
queue.offer(cur.left);
}
if(cur.right != null) {
queue.offer(cur.right);
}
}
res.add(list);
flag = !flag;
}
return res;
}
}