Java solution with complexity analysis


  • 0
    B

    BFS traversal
    time complexity O(n), since there are n nodes.
    space complexity O(n), since the last layer has n/2 node in a full binary tree.

    public class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> result = new ArrayList<>();
            if (root == null) {
                return result;
            }
            Deque<TreeNode> queue = new LinkedList<>();
            queue.addLast(root);
            while (!queue.isEmpty()) {
                int size = queue.size();
                List<Integer> layer = new ArrayList<>();
                while (size > 0) {
                    TreeNode cur = queue.pollFirst();
                    layer.add(cur.val);
                    if (cur.left != null) {
                        queue.addLast(cur.left);
                    }
                    if (cur.right != null) {
                        queue.addLast(cur.right);
                    }
                    size--;
                }
                result.add(layer);
            }
            return result;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.