# [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,#,#,15,7},

    3
/ \
9  20
/  \
15   7


return its level order traversal as:

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

class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
if (!root) return {};
vector<vector<int>> res;
queue<TreeNode*> q{{root}};
while (!q.empty()) {
vector<int> oneLevel;
for (int i = q.size(); i > 0; --i) {
TreeNode *t = q.front(); q.pop();
oneLevel.push_back(t->val);
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
res.push_back(oneLevel);
}
return res;
}
};

class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
levelorder(root, 0, res);
return res;
}
void levelorder(TreeNode* node, int level, vector<vector<int>>& res) {
if (!node) return;
if (res.size() == level) res.push_back({});
res[level].push_back(node->val);
if (node->left) levelorder(node->left, level + 1, res);
if (node->right) levelorder(node->right, level + 1, res);
}
};

Github 同步地址：

https://github.com/grandyang/leetcode/issues/102

Binary Tree Level Order Traversal II

Binary Tree Zigzag Level Order Traversal

Minimum Depth of Binary Tree

Average of Levels in Binary Tree

N-ary Tree Level Order Traversal

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

https://leetcode.com/problems/binary-tree-level-order-traversal/discuss/33445/Java-Solution-using-DFS

https://leetcode.com/problems/binary-tree-level-order-traversal/discuss/33450/Java-solution-with-a-queue-used

https://leetcode.com/problems/binary-tree-level-order-traversal/discuss/114449/A-general-approach-to-level-order-traversal-questions-in-Java

LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2014-10-26 04:57  Grandyang  阅读(28072)  评论(11编辑  收藏  举报