需要的数据结构
vector<vector<int>> //用来存储结果
vector<int> //用来存储每一层节点值
queue<Node*> //一个节点的队列
计算方法
二叉树的层序遍历
/**
* 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>> result;
queue<TreeNode*> que;
if(root != NULL) que.push(root);
while(!que.empty()){
// cout<<"here";
int queSize = que.size();
vector<int> res;
for(int i = 0;i < queSize ;i++){
TreeNode* now = que.front();
que.pop();
res.push_back(now->val);
if(now->left != NULL) que.push(now->left);
if(now->right != NULL) que.push(now->right);
}
result.push_back(res);
}
return result;
}
};
N叉树的层序遍历
给定一个 N 叉树,返回其节点值的层序遍历。(即从左到右,逐层遍历)。
树的序列化输入是用层序遍历,每组子节点都由 null 值分隔(参见示例)。
示例1
输入:root = [1,null,3,2,4,null,5,6]
输出:[[1],[3,2,4],[5,6]]
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<vector<int>> levelOrder(Node* root) {
vector<vector<int>> result;
queue<Node*> que;
if(root != NULL) que.push(root);
while( !que.empty()){
int queSize = que.size();
vector<int> res;
for(int i = 0; i< queSize;i++){
Node * nowNode = que.front();
que.pop();
res.push_back(nowNode->val);
for(int j = 0;j<nowNode->children.size();j++)
que.push(nowNode->children[j]);
}
result.push_back(res);
}
return result;
}
};