A simple level-order traversal using Queue in Java


  • 0
    L
        public List<List<Integer>> levelOrderBottom(TreeNode root) {
            if(root==null) {
                return Collections.EMPTY_LIST;
            }
            
            LinkedList<List<Integer>> list = new LinkedList();
            Queue<TreeNode> queue = new LinkedList();
            queue.add(root);
            while(!queue.isEmpty()) {
                int size = queue.size();
                LinkedList<Integer> ll = new LinkedList();                        
                while(size-- >0) {
                    TreeNode node = queue.poll();
                    ll.add(node.val);
                    if(node.left!=null) {
                        queue.add(node.left);
                    }
                    if(node.right!=null) {
                        queue.add(node.right);
                    }
                }
                list.addFirst(ll);
            }
            
            return list;
        }
    

Log in to reply
 

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