Skip to content

Latest commit

 

History

History
49 lines (42 loc) · 1.1 KB

Binary Tree Level Order Traversal.md

File metadata and controls

49 lines (42 loc) · 1.1 KB

Provided Code

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
}

Solution

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) {
            return new ArrayList();
        }
        List<List<Integer>> lists = new ArrayList();
        Deque<TreeNode> deque = new ArrayDeque(); // use deque as a queue
        deque.add(root);
        while (!deque.isEmpty()) {
            int numNodesInLevel = deque.size();
            List<Integer> level = new ArrayList(numNodesInLevel);
            while (numNodesInLevel-- > 0) {
                TreeNode n = deque.remove();
                level.add(n.val);
                if (n.left != null) {
                    deque.add(n.left);
                }
                if (n.right != null) {
                    deque.add(n.right);
                }
            }
            lists.add(level);
        }
        return lists;
    }
}

Time/Space Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(n)

Links