107. Binary Tree Level Order Traversal II

107. Binary Tree Level Order Traversal II

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List> levelOrderBottom(TreeNode root) {
        if (root == null) return new LinkedList();
        List<List> out = new ArrayList();
Queue   q = new LinkedList(); 
        q.offer(root);
        while(!q.isEmpty()){
            ArrayList current = new ArrayList();
            int size = q.size();//we must put it in variable is the size changes each loop
            for(int i =0; i < size; i++){
            TreeNode c = q.poll();
            if(c != null){
                current.add(c.val);
            if(c.left != null)
                q.offer(c.left);
            if(c.right != null)
                q.offer(c.right);
            }
            
        }
            out.add(current);
        }
         Collections.reverse(out);
        return out;
    }
    
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s