[LeetCode 102] Binary Tree Level Order Traversal

https://leetcode.com/problems/binary-tree-level-order-traversal/

http://www.lintcode.com/zh-cn/problem/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]
]

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
 
 
class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Level order a list of lists of integer
     */
public:
    vector<vector<int>> levelOrder(TreeNode *root) {
        // write your code here
        vector<vector<int> > ret;
        queue<TreeNode *> q;
        
        if (root == NULL) {
            return ret;
        }
        
        q.push(root);
        q.push(NULL);
        
        while (!q.empty() && q.front() != NULL) {
            vector<int> subRet;
            
            while (true) {
                TreeNode *node = q.front();
                
                if (node == NULL) {
                    q.pop();
                    q.push(NULL);
                    break;
                }
                
                if (node->left) {
                    q.push(node->left);
                }
                
                if (node->right) {
                    q.push(node->right);
                }
                
                subRet.push_back(node->val);
                
                q.pop();
            }
            
            ret.push_back(subRet);
        }
        
        return ret;
    }

};
posted @ 2015-05-09 18:31  Acjx  阅读(296)  评论(0编辑  收藏  举报