Binary Tree Level Order Traversal

Code link:

Idea

We can do a BSF against the tree with a queue. The key here is to ensure all the nodes within the same level are added to the same list.

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> results = new ArrayList<>();
        if (root == null) {
            return results;
        }
        
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> numsInLevel = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode current = queue.poll();
                numsInLevel.add(current.val);
                if (current.left != null) {
                    queue.offer(current.left);
                }
                
                if (current.right != null) {
                    queue.offer(current.right);
                }
            }
            
            results.add(numsInLevel);
        }
        
        return results;
    }
}
  • Time: O(n) as we have to process each node once.
  • Space: O(n).
posted on 2021-08-01 22:41  blackraven25  阅读(28)  评论(0)    收藏  举报