# 19.3.4 [LeetCode 102] 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,null,null,15,7],

    3
/ \
9  20
/  \
15   7


return its level order traversal as:

[
[3],
[9,20],
[15,7]
]
 1 class Solution {
2 public:
3     vector<vector<int>> levelOrder(TreeNode* root) {
4         queue<TreeNode*>q, p;
5         vector<vector<int>>ans;
6         if(!root)return ans;
7         int i = 0;
8         q.push(root);
9         while (!q.empty()) {
10             ans.push_back(vector<int>());
11             while (!q.empty()) {
12                 TreeNode*now = q.front(); q.pop();
13                 ans[i].push_back(now->val);
14                 if (now->left)
15                     p.push(now->left);
16                 if (now->right)
17                     p.push(now->right);
18             }
19             q = p;
20             p = queue<TreeNode*>();
21             i++;
22         }
23         return ans;
24     }
25 };
View Code

posted @ 2019-03-04 22:42  TobicYAL  阅读(143)  评论(0编辑  收藏  举报