๐ŸŒ— ๅ‰‘ๆŒ‡ Offer 32 - III. ไปŽไธŠๅˆฐไธ‹ๆ‰“ๅฐไบŒๅ‰ๆ ‘ III

ๅžไฝ›็ซฅๅญ2022ๅนด10ๆœˆ10ๆ—ฅ
  • algorithm
  • Tree
ๅฐไบŽ 1 ๅˆ†้’Ÿ

๐ŸŒ— ๅ‰‘ๆŒ‡ Offer 32 - III. ไปŽไธŠๅˆฐไธ‹ๆ‰“ๅฐไบŒๅ‰ๆ ‘ III

้šพๅบฆ: ๐ŸŒ—

้—ฎ้ข˜ๆ่ฟฐ

img_41.png


่งฃๆณ•

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        // ๆ€่ทฏ๏ผš
        // ๅฑ‚ๅบ้ๅŽ† - ่พ…ๅŠฉ้˜Ÿๅˆ—
        List<List<Integer>> res = new ArrayList<>();
        if(root == null) {
            return res;
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        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);
                }
            }
            flag = !flag;
            res.add(list);
        }
        return res;
    }
}

่พ“ๅ‡บ

img_40.png

ไธŠๆฌก็ผ–่พ‘ไบŽ: 2022/10/10 ไธ‹ๅˆ8:43:48
่ดก็Œฎ่€…: liuxianzhishou