Java level traversal


  • 0
    F
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> lists = new LinkedList<>();
        if (root == null) {
            return lists;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        List<Integer> list;
        TreeNode current;
        while (!queue.isEmpty()) {
            list = new LinkedList<>();
            int n = queue.size();
            for (int i = 0; i < n; i++) {
                current = queue.remove();
                list.add(current.val);
                if (current.left != null) {
                    queue.add(current.left);
                }
                if (current.right != null) {
                    queue.add(current.right);
                }
            }
            lists.add(list);
        }
        return lists;
    }

Log in to reply
 

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