给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]
示例 2:
输入:root = [1]
输出:[[1]]
示例 3:
输入:root = []
输出:[]
提示:
- 树中节点数目在范围 [0, 2000] 内
- -1000 <= Node.val <= 1000## 法1:使用库中的队列结构
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
queue<TreeNode*> que;
if (!root) return ans;
que.push(root);
while (!que.empty()) {
int cursize = que.size();//父节点个数
ans.push_back(vector<int>());// 存储新一层的数据
//取出当前父节点,并将所有的父节点的孩子节点入队
for(int i=1;i<=cursize;i++){
auto node = que.front();
que.pop();
ans.back().push_back(node->val);
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
}
return ans;
}
};
法2:自定义循环队列
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
if (!root) return ans;
//自定义循环队列最大可存储节点个数为2000
int maxSize = 2001;
TreeNode *que[2001];
int front, rear;
front = rear = 0;
rear = (rear + 1) % maxSize;
que[rear] = root;
while (front < rear){
int curLevelNums = rear - front;//当前层父节点数量
ans.push_back(vector<int>());
//取出当前父节点,并将所有的父节点的孩子节点入队
for (size_t i = 0; i < curLevelNums; i++){
front = (front + 1) % maxSize;
auto node = que[front];
ans.back().push_back(node->val);
if (node->left) {
rear = (rear + 1) % maxSize;
que[rear] = node->left;
}
if (node->right) {
rear = (rear + 1) % maxSize;
que[rear] = node->right;
}
}
}
return ans;
}