Leetcode–Binary Tree Level Order Traversal

The Problem:

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

Notes:

  1. Level order traversal is BFS, use a Queue/LinkedList to record each level.

Java Solution

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
       List<List<Integer>> result = new ArrayList<List<Integer>>();
        if(root==null) return result;
        Queue<TreeNode> curLv = new LinkedList<TreeNode>();
        curLv.add(root);
         Queue<TreeNode> nxtLv = new  LinkedList<TreeNode>();
        List<Integer> one = new ArrayList<Integer>();
        while(!curLv.isEmpty() || !nxtLv.isEmpty()){
            while(!curLv.isEmpty()){
                TreeNode top = curLv.poll();
                one.add(top.val);
                if(top.left!= null){
                    nxtLv.add(top.left);
                }
                if(top.right!= null){
                    nxtLv.add(top.right);
                }
            }
            result.add(one);
            one=new ArrayList<Integer>();
            curLv = nxtLv;
            nxtLv = new LinkedList<TreeNode>();
        }
        return result;        
    }
}
Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s