103. Binary Tree Zigzag Level Order Traversal

解法一 Iteration

思路

这道题遍历二叉树的每一层,特殊的是,对于偶数层,要从左至右输出结果;对于奇数层,要从右至左输出结果。
用双向链表进行 BFS 就可以完成遍历。对于偶数层,始终移除双向链表头部节点,然后从左至右添加节点。对于奇数层,始终移除双向链表尾部节点,然后从右至左始终将新节点添加在头部。

代码
class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) return res;

        LinkedList<TreeNode> list = new LinkedList<>();
        list.add(root);
        int level = 0;
        while (!list.isEmpty()) {
            int levelSize = list.size();
            List<Integer> curr = new ArrayList<>();
            for (int i = 0; i < levelSize; i++) {
                if (level % 2 == 0) {
                    TreeNode node = list.removeFirst();
                    curr.add(node.val);
                    if (node.left != null) {
                        list.add(node.left);
                    }
                    if (node.right != null) {
                        list.add(node.right);
                    }
                } else {
                    TreeNode node = list.removeLast();
                    curr.add(node.val);
                    if (node.right != null) {
                        list.addFirst(node.right);
                    }
                    if (node.left != null) {
                        list.addFirst(node.left);
                    }                
                }
            }
            res.add(curr);
            level++;
        }
        return res;
    }
}
复杂度分析
  • 时间复杂度
    • O(n)
  • 空间复杂度
    • O(n) to keep the linkedlist

解法二 Recursion

思路
代码
复杂度分析
  • 时间复杂度
    • 最好情况
    • 最坏情况
    • 平均情况
  • 空间复杂度

Takeaway

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!