102. Binary Tree Level Order Traversal

解法一 Iteration

思路

We can using a queue to store nodes on level. We continue to do a BFS until the queue is empty. A trick here is that , we can denote the length of the root level to be 1. And after searching all the children for a certain level, we denote the size of the queue to be the length of next level.

代码
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> levels = new ArrayList<>();
        if (root == null) {
            return levels;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int level = 0;
        while(!queue.isEmpty()) {
            int length = queue.size();
            levels.add(new ArrayList<Integer>());
            for (int i = 0; i < length; i++) {
                TreeNode node = queue.poll();
                levels.get(level).add(node.val);
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            level++;
        }

        return levels;
    }
}
复杂度分析
  • 时间复杂度
    Since every node has been visited, the time complexity is O(N).
  • 空间复杂度
    Since every node has been added in the list, the space complexity is O(N).

解法二

思路

Using DFS to traverse one node all the way to the leaf. Add the node to corresponding level list. If the current level hasn't been reached when comparing with levels.size(), we add a new level.

代码
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> levels  = new ArrayList<>();
        DFS(root, levels, 0);
        return levels;
    }

    public void DFS(TreeNode root, List<List<Integer>> levels, int level) {
        if (root == null) {
            return;
        }
        // We include the equal because the root is 0 level so if we have the level in levels list, the actual level size is level.size() + 1 
        if (levels.size() <= level) {
            levels.add(new ArrayList<Integer>());
        }
        levels.get(level).add(root.val);

        DFS(root.left, levels, level + 1);
        DFS(root.right, levels, level + 1);
    }
}
复杂度分析
  • 时间复杂度
    Since every node has been visited, the time complexity is O(N).
  • 空间复杂度
    Since every node has been added in the list, the space complexity is O(N).

Takeaway

  • Iteration 解法的巧妙之处在于判断了每层节点有几个。
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

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