题目: 给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]
示例 2:
输入:root = [1]
输出:[[1]]
示例 3:
输入:root = []
输出:[]
思路:
使用队列实现二叉树的层序遍历;将每一层的结果存放到一个二维的vector数组中;首先应该判断 root 是否为空,如果不为空则入队,当队列不为空时,一直循环,计算当前队列中的结点个数为size,在内层循环中使用,这样就知道每一层的节点个数对应的就循环几次,每循环一次,将队列出队一次,并将值添加到一维vector中,最后将该节点的左右孩子入队列,在下一轮的while循环中,重新计算size的大小,进行下一层的元素个数统计。
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x):val(x),left(NULL),right(NULL){}
};
class Solution {
public:
vector<vector<int>> Binorder(TreeNode* root) {
queue<TreeNode*> que;
if (root != NULL) {
que.push(root);
}
vector<vector<int>> result;
while (!que.empty()) {
int size = que.size();
vector<int> vec;
for (int i = 0; i < size;i++) {
TreeNode* node = que.front();
que.pop();
vec.push_back(node->val);
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
result.push_back(vec);
}
return result;
}
};
int main() {
TreeNode* A = (TreeNode*)malloc(sizeof(TreeNode));
A->val = 5;
A->left = NULL;
A->right = NULL;
TreeNode* B = (TreeNode*)malloc(sizeof(TreeNode));
B->val = 3;
B->left = NULL;
B->right = NULL;
TreeNode* C = (TreeNode*)malloc(sizeof(TreeNode));
C->val = 6;
C->left = NULL;
C->right = NULL;
TreeNode* D = (TreeNode*)malloc(sizeof(TreeNode));
D->val = 2;
D->left = NULL;
D->right = NULL;
TreeNode* E = (TreeNode*)malloc(sizeof(TreeNode));
E->val = 4;
E->left = NULL;
E->right = NULL;
A->left = B;
A->right = C;
B->left = D;
B->right = E;
Solution ss;
vector<vector<int>> rres = ss.Binorder(A);
for (vector<vector<int>>::iterator pos = rres.begin(); pos != rres.end();pos++) {
for (vector<int>::iterator ppos = (*pos).begin(); ppos != (*pos).end();ppos++) {
cout << *ppos << " ";
}
cout << endl;
}
return 0;
}