题目:
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] ]
思路:
这也是一道典型的BFS的题目,采用队列这种数据结构,逐层添加即可。在实现中,我采用的小技巧是:在队列中插入NULL值来分割不同的层次。这样当队头元素为NULL时,我们就知道已经遍历完成了一个层次了。
代码:
/**
* Definition for a binary tree node.
* 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) {
if (root == NULL) {
return {};
}
vector<vector<int>> ret;
queue<TreeNode*> q;
q.push(root);
q.push(NULL); // separator
vector<int> line;
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
if (node == NULL) {
ret.push_back(line);
line.clear();
if (!q.empty()) {
q.push(NULL);
}
}
else {
line.push_back(node->val);
if (node->left) {
q.push(node->left);
}
if (node->right) {
q.push(node->right);
}
}
}
return ret;
}
};
本文介绍了一种经典的二叉树层次遍历算法,并通过使用队列数据结构实现了从左到右、按层遍历的功能。该算法适用于多种应用场景。
385

被折叠的 条评论
为什么被折叠?



