Java solution using LinkedList as Queue.


  • 2
    O
    
        public List<List<Integer>> levelOrderBottom(TreeNode root) {
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            List<Integer> list;
            ArrayList<TreeNode> q = new ArrayList<TreeNode>();
            if (root != null) {
                q.add(root);
            }
            int size;
            TreeNode tmp;
            while(!q.isEmpty()) {
                size = q.size();
                list = new ArrayList<Integer>();
                while(size > 0) {
                    tmp = q.remove(0);
                    if (tmp.left != null) {
                        q.add(tmp.left);
                    }            
                    if(tmp.right != null) {
                        q.add(tmp.right);
                    }
                    list.add(tmp.val);
                    size--;
                }
                result.add(0, list);
            }
            return result;
        }
    

Log in to reply
 

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