Sunday, October 13, 2013

Day 50, ##, Gas Station

Gas Station
There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.
Note:
The solution is guaranteed to be unique.
---------------------------------------------------------
O(n) time, in space
if gas[i] < cost[i], skip to i + 1, reset everything
else, add the difference to the gas[i + 1] station, repeat
until all stations have been checked.
 Note that count < size + 1 since this is supposed to be a loop
class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int startPoint = -1, gasLeft = 0;
        int size = gas.size();
        for (int i = 0, count = 0; i < size && count < size + 1; i++, count++) {
            if (i == startPoint) return i; // found a start point
            gasLeft += gas[i];
            if (gasLeft >= cost[i]) {
                if (startPoint == -1) {
                    startPoint = i;
                }
                gasLeft -= cost[i];
                if (i == size - 1) {
                    i = -1;
                }
            }else { // reset 
                gasLeft = 0;
                startPoint = -1;
            }
        }
        return startPoint;
    }
};
----------------------------
Neat version, from internet
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
  int sum = 0;
  int total = 0;
  int j = -1;
  for(int i = 0; i < gas.size() ; ++i){
    sum += gas[i]-cost[i];
    total += gas[i]-cost[i];
    if(sum < 0){
      j=i; sum = 0; 
    }
  }
  return total>=0? j+1 : -1;
}
Update on Oct-29-2014
If car starts at A and can not reach B. Any station between A and B can not reach B.(B is the first station that A can not reach.
The solution below is not completely correct, it cannot pass the case where total cost is larger than gas, for instance: gas = {5,5,1,2,4} cost = {4,4,4,4,4}. Although OJ accepts it
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        int leftGas = 0;
        int index = -1;
        
        for (int i = 0; i < gas.size(); i++) {
            if (index == -1) index = i;
            leftGas += gas[i] - cost[i];
            if (leftGas < 0) {
                index = -1;
                leftGas = 0;
            }
        }
        
        if (leftGas + gas[0] - cost[0] < 0) return -1;
        
        return index;
    }
};

Saturday, October 12, 2013

Day 49, #127, #131, Word Ladder, Palindrome Partitioning

Word Ladder
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the dictionary
For example,
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]

As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
Note:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.
------------------------------------------------------------------------
typical BFS and shortest path
class Solution {
public:
    int ladderLength(string start, string end, unordered_set<string> &dict) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if (start == end) return 1;
        queue<pair<string,int> > q;
        q.push(make_pair(start, 1)); // assign each node a distance
        unordered_set<string> used;
        while (!q.empty()) {
            string top = q.front().first;
            int length = q.front().second;
            q.pop();
            for (int index = 0; index < start.length(); index++ ) {
                for (int alp = 'a'; alp < 'z'; alp++) {
                    if (alp == top[index]) continue; // ignore the same letter
                    string temp = top;
                    temp[index] = alp;
                    if (temp == end) {
                        return length+1;
                    }
                    if (used.find(temp) == used.end() && dict.find(temp) != dict.end()) {
                        used.insert(temp);
                        q.push(make_pair(temp, length+1));
                    }
                    
                }
            }
        }
        return 0;
    }
};
Java,双向BFS, udpated on Aug-4th-2018
class Solution {
    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        int len = 1;
        Map<String, Boolean> dic = getDic(wordList);
        if (!dic.containsKey(endWord)) return 0;
        
        dic.put(beginWord, false);
        dic.put(endWord, false);
        Set<String> begin = new HashSet<>();
        Set<String> end = new HashSet<>();
        begin.add(beginWord);
        end.add(endWord);
        
        while (!begin.isEmpty() && !end.isEmpty()) {
            if (begin.size() > end.size()) {
                Set<String> t = begin;
                begin = end;
                end = t;
            }
            
            len++;
            Set<String> temp = new HashSet<>();
            for (String s : begin) {
                for (int i = 0; i < s.length(); i++) {
                    char c = s.charAt(i);
                    for (char nextC = 'a'; nextC <= 'z'; nextC++) {
                        String next = s.substring(0, i) + nextC + s.substring(i + 1);

                        if (end.contains(next)) return len;

                        if (dic.containsKey(next) && dic.get(next)) {
                            temp.add(next);
                            dic.put(next, false);
                        }
                    }
                }
            }
            
            begin = temp;
        }
        
        return 0;
    }
    
    private Map<String, Boolean> getDic(List<String> wordList) {
        Map<String, Boolean> dic = new HashMap<>();
        
        for (String s : wordList) {
            dic.put(s, true);
        }
        
        return dic;
    }
}
Palindrome Partitioning
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab",
Return
  [
    ["aa","b"],
    ["a","a","b"]
  ]
-----------------------------------------
DFS, recursive
class Solution {
public:
    bool checkPalin (string s) {
        for (int i = 0; i < s.length()/2; i++) {
            int end = s.length() - 1 - i;
            if (s[i] != s[end]) {
                return false;
            }
        }
        return true;
    }
    
    void partition (string cur, vector<string> v, string remain,  vector<vector<string> >& ret) {
        if (remain.empty()) {
            ret.push_back(v);
            return;
        }
        
        for (int i = 0; i < remain.length(); i++) {
            cur += remain[i];
            if (checkPalin(cur)) {
                vector<string> cp = v; 
                cp.push_back(cur);
                partition("",cp,remain.substr(i+1),ret);
            }
        }
    }
    
    vector<vector<string>> partition(string s) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        vector<vector<string> > ret;
        vector<string> v;
        partition("",v,s,ret);
        return ret;
    }
};
Update on Oct-03-2014
Using index
class Solution {
public:
    bool isPal(string str) {
        for (int i = 0; i < str.length() / 2; i++) {
            if (str[i] != str[str.length() - 1 - i]) {
                return false;
            }
        }
        
        return true;
    }
    
    void dfs(vector<vector<string> > &rt, vector<string> cur, string s,int index) {
        if (index == s.length()) {
            rt.push_back(cur);
            return;
        }
        for (int i = 1; i < s.length() - index + 1; i++) {
            string sub = s.substr(index,i);    
            if (isPal(sub)) {
                vector<string> temp = cur;
                temp.push_back(sub);
                dfs(rt,temp,s,index + i);
            }
        }
    
    }
    
    vector<vector<string>> partition(string s) {
        vector<vector<string> > rt;
        vector<string> v;
        dfs(rt,v,s,0);
        return rt;
    }
};
Thoughts: we can add Memoization to improve efficiency. Set up a 2d-array of vector<vector<string> >, [i][j] contains all palindrome partitionings between i and j

Friday, October 11, 2013

Day 48, #116, #120, #123, Populating Next Right Pointers in Each Node, Triangle, Best Time to Buy and Sell Stock II

Populating Next Right Pointers in Each Node
Given a binary tree
    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Note:
  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,

         1
       /  \
      2    3
     / \  / \
    4  5  6  7
After calling your function, the tree should look like:

         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \  / \
    4->5->6->7 -> NUL
-----------------------------------------------------------------
 typical level order tree traversal, can be implemented with either DFS or BFS
using an array to store the current tailing nodes, one slot for each level
/**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  TreeLinkNode *left, *right, *next;
 *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 * };
 */
class Solution {
public:
    void traverse (TreeLinkNode* root, int curlevel, vector<TreeLinkNode*>& v) {
        if (root == NULL) {
            return;
        } 
        if (v.size() < curlevel) {
            v.push_back(root);
        }else{
            v[curlevel-1]->next = root;
            v[curlevel-1] = root;
        }
        traverse(root->left,curlevel+1,v);
        traverse(root->right,curlevel+1,v);
    }
    
    void connect(TreeLinkNode *root) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        vector<TreeLinkNode*> v;
        traverse(root,1,v);
    }
};

constant space
/**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  TreeLinkNode *left, *right, *next;
 *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 * };
 */
class Solution {
public:
    void connect(TreeLinkNode *root) {
        while (root != NULL) {
            TreeLinkNode *pre = root;
            TreeLinkNode *before = NULL;
            while (pre != NULL && pre->left != NULL) {
                if (before != NULL) {
                    before->next = pre->left;
                }
                pre->left->next = pre->right;
                before = pre->right;
                pre = pre->next;
            }
            root = root->left;
        }
    }
};

Triangle

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle

[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.
--------------------------------------------
DP in place
replace each element in level #i with the possible minimum sum that are added from level #i+1
class Solution {
public:
    int minimumTotal(vector<vector<int> > &triangle) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int size = triangle.size();
        for (int row = size - 2; row >= 0; row--) {
            for (int index = 0; index < triangle[row].size(); index++) {
                triangle[row][index] += min(triangle[row+1][index],triangle[row+1][index+1]);
            }
        }
        return triangle[0][0];
    }
};
Best Time to Buy and Sell Stock II
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
-----------------------------------------------------------------------
greedy
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int sum = 0;
        for (int i = 1; i < prices.size(); i++) {
            int dif = prices[i] - prices[i - 1];
            if (dif > 0) {
                sum += dif;
            }
        }
        return sum;
    }
};

Day 47, #105, #106, #107, #114 Construct Binary Tree from Preorder and Inorder Traversal, Construct Binary Tree from Inorder and Postorder Traversal, Binary Tree Level Order Traversal II, Flatten Binary Tree to Linked List

Construct Binary Tree from Preorder and Inorder Traversal
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
-----------------------------------------------
Explaination 
Having a start and an end pointer for each array.
Using hash table to track the root position in inorder array.
For preorder array, the first in partition is always the root node, for inorder one, in a given partition, all nodes whose indexes are less than root's are belong to its left child, whose indexes are greater than root's, belongs to its right child
Same algorithm for Postorder and Inorder combination

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void hashMapping(vector<int> &inorder, unordered_map<int,int>& mapping){
        for (int i = 0; i < inorder.size(); i++) {
            int k = inorder[i];
            mapping[k] = i;
        }
    }
    
    TreeNode *rec(vector<int> &preorder, vector<int> &inorder, int startP, int endP, int startI, int endI,unordered_map<int,int>& mapping) {
        //if (endI < startI || endP < startP)return NULL;
        int rootIndex = mapping[preorder[startP]];
        TreeNode *root = new TreeNode(preorder[startP]);
        // delimiter for preorder
        int delimiterIndex = rootIndex - startI + startP; 
        if (rootIndex > startI) {
            root->left = rec(preorder,inorder,startP+1,delimiterIndex,startI,rootIndex - 1,mapping);
        }else {
            root->left=NULL;
        }
        if (rootIndex < endI) {
            root->right = rec(preorder,inorder,delimiterIndex + 1,endP,rootIndex + 1,endI,mapping);
        }else {
            root->right=NULL;
        }
        return root;
    }
    
    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if (preorder.size() == 0) return NULL;
        unordered_map<int,int> mapping;
        hashMapping(inorder,mapping);
        return rec(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1,mapping);
    }
};
Construct Binary Tree from Inorder and Postorder Traversal
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
-----------------------------
Similar to Preorder and Inorder combination
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void hashMapping(vector<int> &inorder, unordered_map<int,int>& mapping){
        for (int i = 0; i < inorder.size(); i++) {
            int k = inorder[i];
            mapping[k] = i;
        }
    }

    TreeNode *rec(vector<int> &postorder, vector<int> &inorder, int startP, int endP, int startI, int endI,unordered_map<int,int>& mapping) {
        //if (endI < startI || endP < startP)return NULL;
        int rootIndex = mapping[postorder[endP]];
        TreeNode *root = new TreeNode(postorder[endP]);
        // delimiter for postorder
        int delimiterIndex = rootIndex - startI + startP-1; 
        if (rootIndex > startI) {
            root->left = rec(postorder,inorder,startP,delimiterIndex,startI,rootIndex - 1,mapping);
        }else {
            root->left=NULL;
        }
        if (rootIndex < endI) {
            root->right = rec(postorder,inorder,delimiterIndex + 1,endP-1,rootIndex + 1,endI,mapping);
        }else {
            root->right=NULL;
        }
        return root;
    }

    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if (postorder.size() == 0) return NULL;
        unordered_map<int,int> mapping;
        hashMapping(inorder,mapping);
        return rec(postorder,inorder,0,postorder.size()-1,0,inorder.size()-1,mapping);
    }
};
Binary Tree Level Order Traversal II
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7
return its bottom-up level order traversal as:

[
  [15,7]
  [9,20],
  [3],
] 
----------------------------------
Similar to #102 Binary Tree Level Order Traversal
This is a DFS solution 
 
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    

vector<vector<int> > levelOrderBottom(TreeNode *root) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function
    vector<vector<int>> result;
    traverse(root, 1, result);
    std::reverse(result.begin(), result.end());
    return result;
}

void traverse(TreeNode *root, int level, vector<vector<int>> &result) {
    if (root == NULL) {
        return;
    }
    
    if (level > result.size()) {
        vector<int> v;
        result.push_back(v);
    }
    
    result[level-1].push_back(root->val);
    traverse(root->left,level+1,result);
    traverse(root->right,level+1,result);
}
};

Flatten Binary Tree to Linked List
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
         1
        / \
       2   5
      / \   \
     3   4   6
The flattened tree should look like:
   1
    \
     2
      \
       3
        \
         4
          \
           5
            \
             6
----------------------------------------------------------
Solution #1, not in place, preorder traverse the tree, store each node in an array,

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void traverse (TreeNode *root, vector<TreeNode*>& v) {
        if (root != NULL) {
            v.push_back(root);
            traverse(root->left,v);
            traverse(root->right,v);
        }
    }

    void flatten(TreeNode *root) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        vector<TreeNode*> v;
        traverse(root,v);
        TreeNode *itr = root;
        for (int i = 1; i < v.size(); i++) {
            itr->right = v[i];
            itr->left = NULL;
            itr = itr->right;
        }
    }
};
Solution #2, in place iterative.
Same logic can be adopted in recursive implementation
O(n), 在inner loop里面,在整段代码的执行过程中每个node只出现过一次
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode *root) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        TreeNode* ret = root;
        while (root != NULL) {
            if (root->left != NULL) {
                TreeNode *right = root->right;
                TreeNode *mostRight = root->left;
                
                while (mostRight->right != NULL) {
                    mostRight = mostRight->right;
                }
                mostRight->right = right;
                root->right = root->left;
                root->left = NULL;
            }
            root = root->right;
        }
        root = ret;
    }
};
Update on Sep-28-2014
Recursive solution, Pre-Order tree traversal
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* f(TreeNode *root, TreeNode *newRoot) {
        if (root == NULL) return newRoot;
        TreeNode *tempRight = root->right;
        newRoot->right = root;
        
        TreeNode *t = f(root->left,root); // return the end of list
        root->left = NULL;
        TreeNode *t2 = f(tempRight,t);
        return t2;
    }

    void flatten(TreeNode *root) {
        TreeNode *newRoot = root;
        TreeNode *dummy = new TreeNode(0);

        f(newRoot,dummy);
    }
};

Updated on Sep-24th-2018
跟上面类似思路,更易懂的写法。getEndOfList(root)返回以root为顶点的sub-tree转换成为list之后的最尾端的点
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    public void flatten(TreeNode root) {
        if (root == null) return;
        getEndOfList(root);
    }
    
    private TreeNode getEndOfList(TreeNode root) {

        TreeNode l = root.left;
        TreeNode r = root.right;
        if (root.left != null) {
            TreeNode end = getEndOfList(root.left);
            root.right = l;
            l = end;
            end.right = r;
            root.left = null;
        }
        
        if (r != null) {
            return getEndOfList(r);
        }
        if (l == null) {
            return root;
        }
        return l;   
    }
}

Wednesday, October 9, 2013

Day 46, ##, #102 Copy List with Random Pointer, Binary Tree Level Order Traversal

Copy List with Random Pointer
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
------------------------------------------
The key point here is to set a direct link between the original node and its duplicate. So during the second iteration, the new/duplicate *next and *random nodes can be traced by their original nodes.

Besides using a map, the link can be implemented by attaching each duplicate right after to its original node in the linked list.

/**
 * Definition for singly-linked list with a random pointer.
 * struct RandomListNode {
 *     int label;
 *     RandomListNode *next, *random;
 *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
 * };
 */
class Solution {
public:
    RandomListNode *copyRandomList(RandomListNode *head) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if (head == NULL) return NULL;
        RandomListNode *ret = head, *itr = head;
        unordered_map<RandomListNode*,RandomListNode*> mapping;
        // set up the relationship between orignial and its duplicates
        while (itr != NULL) {
            RandomListNode *dup = new RandomListNode(itr->label);
            mapping[itr] = dup;
            itr = itr->next;
        }
        itr = head;
        // second iteration, set up *next and *random for duplicates
        while (itr != NULL) {
            RandomListNode *dup = mapping[itr];
            dup->next = mapping[itr->next];
            dup->random = mapping[itr->random];
            itr= itr->next;
        }
        return mapping[head];
    }
};

Binary Tree Level Order Traversal
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]
]
--------------------------------------------
Solution #1 iterativ
Typical breadth first search, keep two queues to track all the nodes, use an integer to determine which should be used for current iteration
Challenge: use DFS to solve this 
check #107 Binary Tree Level Order Traversal II for DFS recursive solution
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void foo (queue<TreeNode*>& cur, queue<TreeNode*>& next, vector<int>& level) {
        while (!cur.empty()) {
            TreeNode* current = cur.front();
            cur.pop();
            level.push_back(current->val);
            if (current->left != NULL) {
                next.push(current->left);
            }
            if (current->right != NULL) {
                next.push(current->right);
            }
        }
    }

    vector<vector<int> > levelOrder(TreeNode *root) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        queue<TreeNode*> que,p;
        vector<vector<int> > ret;
        if (root == NULL) return ret;
        int levelCount = 0;
        que.push(root);
        while (!que.empty() || !p.empty()) {
            vector<int> level;
            if (levelCount % 2 == 0) {
                foo(que,p,level);
            }else {
                foo(p,que,level);
            }
            ret.push_back(level);
            levelCount++;
        }
        return ret;
    }
};
Update on Sep-24-2014 
refactoried
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void traverse(vector<vector<int> > &rt, queue<TreeNode*> &q1, queue<TreeNode*> &q2) {
        vector<int> v;
        while (!q1.empty()) {
            TreeNode * top = q1.front();
            q1.pop();
            v.push_back(top->val);
            if (top->left != NULL) q2.push(top->left);
            if (top->right != NULL) q2.push(top->right);
            
        }
        
        rt.push_back(v);
    }

    vector<vector<int> > levelOrder(TreeNode *root) {
        vector<vector<int> > rt;
        if (root == NULL) return rt;
        queue<TreeNode*> q1;
        queue<TreeNode*> q2;
        q1.push(root);
        
        while (!q1.empty() || !q2.empty()) {
            if (!q1.empty()) {
                traverse(rt,q1,q2);
            }
            if (!q2.empty()) {
                traverse(rt,q2,q1);
            }
        }
        
        return rt;
    }
};
Update on Sep-26-2014 
DFS
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void dfs(vector<vector<int> > &rt, int level, TreeNode *root) {
        if (root == NULL) return;
        
        if (rt.size() < level) {
            vector<int> v;
            rt.push_back(v);
        }
        
        rt[level - 1].push_back(root->val);
        dfs(rt,level + 1, root->left);
        dfs(rt,level + 1, root->right);
        
    }

    vector<vector<int> > levelOrder(TreeNode *root) {
        vector<vector<int> > rt;
        dfs(rt,1,root);
        return rt;
    }
};
Java, updated on Jul-30th-2018
/**
 * 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<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> rt = new ArrayList<>();
        if (root == null) return rt;
        
        Queue<TreeNode> que = new LinkedList<>();
        que.add(root);
        int size = 1;
        rt.add(new ArrayList<>());
        
        while (!que.isEmpty()) {
            if (size == 0) {
                rt.add(new ArrayList<>());
                size = que.size();
            }
            
            size--;
            TreeNode node = que.poll();
            rt.get(rt.size() - 1).add(node.val); 
            if (node.left != null) que.add(node.left);
            if (node.right != null) que.add(node.right);
        }
        
        return rt;
    }
}