JAVA using a queue in 2ms


  • 0
    S
        public List<List<Integer>> levelOrderBottom(TreeNode root) {
            List<List<Integer>> arr = new ArrayList<List<Integer>>();
            if(root == null)
                return arr;
            getBottomOrder(root, arr);
            reverseArray(arr);
            return arr;
        }
        private void getBottomOrder(TreeNode root, List<List<Integer>> arr) {
            Queue<TreeNode> q = new LinkedList<>();
            q.add(root);
            while(!q.isEmpty()) {
                int size = q.size();
                List<Integer> result = new ArrayList<Integer>();
                for(int i = 0; i < size; i++) {
                    TreeNode node = q.poll();
                    result.add(node.val);
                    if(node.left != null)
                        q.add(node.left);
                    if(node.right != null)
                        q.add(node.right);
                }
                arr.add(result);
            }
        }
        private void reverseArray(List<List<Integer>> arr) {
            int size = arr.size();
            for(int i = 0; i < size/2 ; i++) {
                List<Integer> result = arr.get(i);
                arr.set(i, arr.get(size - i - 1));
                arr.set(size - i - 1, result);
            }
        }
    }

Log in to reply
 

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