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实现树的层次遍历,使用迭代而非递归的方法,在每一次搜索节点的同时维护一个代表层数的变量,在搜索一个子节点时,将该节点加入一个vector,同时将一个代表层数的另一个变量储存在另一个vector中。这两个vector模仿的时队列的先进先出的功能。当储存节点的vector的大小为空时,则说明遍历完成。
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> answer;
if (root == NULL) return answer;
vector<TreeNode*> trlist;
vector<int> floor;
trlist.push_back(root);
floor.push_back(0);
while (!trlist.empty()) {
TreeNode* temp = trlist[0];
int ceng = floor[0];
while (ceng >= answer.size()) {
vector<int> temp;
answer.push_back(temp);
}
answer[ceng].push_back(temp->val);
if (temp->left) {
trlist.push_back(temp->left);
int t = ceng + 1;
floor.push_back(t);
}
if (temp->right) {
trlist.push_back(temp->right);
int t = ceng + 1;
floor.push_back(t);
}
trlist.erase(trlist.begin());
floor.erase(floor.begin());
}
return answer;
}
};