LeetCode: 102. Binary Tree Level Order Traversal
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]
]
题目大意: 输出给定二叉树的层次遍历序列。
解题思路 —— BFS
BFS 搜索二叉树,并用空指针(nullptr
) 将每层元素分割。
AC 代码
/** * 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) {
vector<vector<int>> leverOrderSequence; // 保存层次遍历序列
vector<int> curLevel; // 保存当前层的序列
queue<TreeNode*> que; // BFS 队列
que.push(root); // 将根节点加入 BFS 对列
que.push(nullptr); // 用 nullptr 来隔开每一层的元素
while(!que.empty())
{
TreeNode* curNode = que.front();
que.pop();
if(curNode == nullptr && curLevel.empty())
{
continue;
}
else if(curNode == nullptr && !curLevel.empty())
{
que.push(nullptr);
leverOrderSequence.push_back(curLevel);
curLevel.clear();
}
else
{
curLevel.push_back(curNode->val);
if(curNode->left != nullptr) que.push(curNode->left);
if(curNode->right != nullptr) que.push(curNode->right);
}
}
return leverOrderSequence;
}
};