---
title: "[Leetcode] Binary Tree Level Order Traversal"
author: "cozilla"
date: "2013-09-10T14:39:15Z"
tags: []
categories: ["非技术"]
slug: "leetcode-binary-tree-level-order-traversal"
draft: false
lastmod: "2013-09-10T14:39:15Z"
id: 1940095
url: "https://cozilla.iteye.com/blog/1940095"
---

**Binary Tree Level Order Traversal**Sep 29 '125832 / 14746

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]
]
```

 

```
/**
 * 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> > levelOrder(TreeNode *root) {
        vector<vector<int> > res;
        if (root == NULL) return res;
        queue<TreeNode*> q;
        int cur = 1, next = 0;
        q.push(root);
        vector<int> a;
        while (!q.empty()) {
            auto tmp = q.front();
            q.pop();
            
            a.push_back(tmp->val);
            cur--;
            if (tmp->left != NULL) q.push(tmp->left), next++;
            
            if (tmp->right != NULL) q.push(tmp->right), next++;
            if (cur == 0) {
                cur = next;
                next = 0;
                res.push_back(a);
                a.clear();
            }
        }
        //if (a.size() > 0) res.push_back(a);
        return res;
    }
};
```