🌗 103. 二叉树的锯霿圢层序遍历

吞䜛童子2022幎10月10日
  • algorithm
  • tree
  • 层序遍历
小于 1 分钟

🌗 103. 二叉树的锯霿圢层序遍历

隟床: 🌗

问题描述

img_8.png


解法

/**
 * 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;
    }
}

蟓出

img_7.png

䞊次猖蟑于: 2022/10/10 䞋午8:43:48
莡献者: liuxianzhishou