链表的创建:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
struct ListNode {
int val; //存储数据
ListNode* next; //next指针
ListNode():val(0),next(NULL){} //构造函数
ListNode(int x) :val(x), next(NULL) {}
};
int main(){
ListNode* head ,*p;
int val[] = {1,2,3,4,5,6};
head = new ListNode(val[0]);
p = head;
for(int i = 1 ; i < 6 ;i++){
ListNode *tp = new ListNode(val[i]);
p->next = tp;
p = tp;
}
p->next = NULL;
while(head){
cout<<head->val<<" ";
head = head->next;
}
return 0;
}
代码输出结果:
二叉树的创建
#include <bits/stdc++.h>
using namespace std;
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) {}
};
//二叉树的层序遍历
void level(TreeNode* root,vector<vector<int>> &a){
queue<TreeNode*>qu;
qu.push(root);
while(!qu.empty()){
//k 为该层的节点数量
int k = qu.size();
vector<int>tp;
for(int i = 1;i<=k;i++){
TreeNode* e = qu.front();
qu.pop();
tp.push_back(e->val);
if(e->left != NULL){
qu.push(e->left);
}
if(e->right != NULL){
qu.push(e->right);
}
}
a.push_back(tp);
}
}
int main(){
//建树
TreeNode *root = new TreeNode(0);
TreeNode *A = new TreeNode(1);
TreeNode *B = new TreeNode(2);
TreeNode *C = new TreeNode(3);
root->left = A;
root->right = B;
A->left = C;
//层次遍历
vector<vector<int>> a;
if(root == NULL){
return 0;
}
level(root,a);
for(auto x:a){
for(auto y : x){
cout<<y<<" ";
}
cout<<endl;
}
return 0;
}
代码输出结果: