103. 二叉树的锯齿形层序遍历
解题思路
- 改造二叉树的层次遍历算法
- 设置一个控制变量进行控制方向
java
/**
* 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>> result = new ArrayList<>();
if(root == null){
return result;
}
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);// 入队
boolean flag = true;// 从左向右
while(!q.isEmpty()){
int size = q.size();
LinkedList<Integer> list = new LinkedList<>();
// 遍历当前层
for(int i = 0; i < size; i++){
// 出队
TreeNode cur = q.poll();
// list.add(cur.val);
if(flag == true){
list.addLast(cur.val);
}else{
list.addFirst(cur.val);
}
if(cur.left != null){
q.offer(cur.left);
}
if(cur.right != null){
q.offer(cur.right);
}
}
result.add(list);
flag = !flag;
}
return result;
}
}