美文网首页
从上到下打印二叉树 III

从上到下打印二叉树 III

作者: 曾大稳丶 | 来源:发表于2022-04-24 10:21 被阅读0次

题目链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof/

image.png

题目分析
采用BFS+双端队列即可。奇数层添加到队列头部,偶数层添加到队列尾部。

public class TreeNode {
       int val;
       TreeNode left;
       TreeNode right;
       TreeNode(int x) { val = x; }
    }

public List<List<Integer>> levelOrder(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> res = new ArrayList<>();
        if(root != null) queue.add(root);
        while(!queue.isEmpty()) {
            LinkedList<Integer> tmp = new LinkedList<>();
            for(int i = queue.size(); i > 0; i--) {
                TreeNode node = queue.poll();
                if(res.size() % 2 == 0) tmp.addLast(node.val); // 偶数层 -> 队列头部
                else tmp.addFirst(node.val); // 奇数层 -> 队列尾部
                if(node.left != null) queue.add(node.left);
                if(node.right != null) queue.add(node.right);
            }
            res.add(tmp);
        }
        return res;
    }

复杂度分析
空间复杂度: O(N)。
时间复杂度: O(N)。

相关文章

网友评论

      本文标题:从上到下打印二叉树 III

      本文链接:https://www.haomeiwen.com/subject/ubctyrtx.html