二叉树的层序遍历
// 二叉树的层序遍历(使用链式队列) #include<stdio.h> #include<stdlib.h> #include<stdbool.h> //定义二叉树的结点 typedef struct BiTNode{ char data; //结点数据 struct BiTNode *lchild; //左孩子指针 struct BiTNode *rchild; //右孩子指针 }BiTNode,*BiTree; //定义队列的结点 typedef struct QNode{ BiTNode *data; //存二叉树结点的指针 struct QNode *next; //next指针 }QNode; //定义队列 typedef struct Queue{ QNode *front; //队头指针 QNode *rear; //队尾指针 }Queue; //初始化队列(带头结点) void InitQueue(Queue *Q){ Q->front=Q->rear=(QNode*)malloc(sizeof(QNode)); //front,rear指向头结点 Q->front->next=NULL; } //队列判空 bool QueueEmpty(Queue *Q){ return Q->front->next==NULL; } //入队 void EnQueue(Queue *Q,BiTNode *x){ QNode *p=(QNode*)malloc(sizeof(QNode)); p->data=x; p->next=NULL; Q->rear->next=p; Q->rear=p; } //出队 void DeQueue(Queue *Q){ QNode *p=Q->front->next; Q->front->next=p->next; if(Q->rear==p) //只有一个元素 Q->rear=Q->front; //rear指向头结点 free(p); } //取队头 BiTNode *QueueFront(Queue *Q){ return Q->front->next->data; } //层序遍历 void LevelOrder(BiTNode *root){ Queue *Q=(Queue*)malloc(sizeof(Queue)); InitQueue(Q); //初始化队列 EnQueue(Q,root); //二叉树的根指针入队 while(!QueueEmpty(Q)){ BiTNode *p=QueueFront(Q); //取出队头元素 printf("%c ",p->data); DeQueue(Q); //队头元素出队 if(p->lchild) EnQueue(Q,p->lchild); //左孩子指针入队 if(p->rchild) EnQueue(Q,p->rchild); //右孩子指针入队 } } //用串先序递归构建二叉树 int sc=0; //全局变量sc, 枚举串 BiTree CreateBiTree(char *s){ //s为先序遍历串 BiTree T; if(s[sc]=='^') T=NULL; else{ T=(BiTree)malloc(sizeof(BiTNode)); T->data=s[sc++]; T->lchild=CreateBiTree(s); sc++; T->rchild=CreateBiTree(s); } return T; } int main(){ char s[]="ABD^^EG^^^CF^H^^^"; BiTree T=CreateBiTree(s); LevelOrder(T); //层序遍历 return 0; }
// 二叉树的层序遍历(使用顺序队列) #include<stdio.h> #include<stdlib.h> #include<stdbool.h> //定义二叉树的结点 typedef struct BiTNode{ char data; //结点数据 struct BiTNode *lchild; //左孩子指针 struct BiTNode *rchild; //右孩子指针 }BiTNode,*BiTree; //层序遍历 #define MAXN 100 void LevelOrder(BiTree T){ BiTNode *Queue[MAXN]; int front=0,rear=0; if(T == NULL) return; Queue[++rear] = T; while(front != rear){ BiTNode *p = Queue[++front]; printf("%c ", p->data); if(p->lchild) Queue[++rear] = p->lchild; if(p->rchild) Queue[++rear] = p->rchild; } } //用串先序递归构建二叉树 int sc=0; //全局变量sc, 枚举串 BiTree CreateBiTree(char *s){ //s为先序遍历串 BiTree T; if(s[sc]=='^') T=NULL; else{ T=(BiTree)malloc(sizeof(BiTNode)); T->data=s[sc++]; T->lchild=CreateBiTree(s); sc++; T->rchild=CreateBiTree(s); } return T; } int main(){ char s[]="ABD^^EG^^^CF^H^^^"; BiTree T=CreateBiTree(s); LevelOrder(T); //层序遍历 return 0; }
//C++ 使用 vector,queue 更方便 class Solution { public: vector<vector<int>> levelOrder(TreeNode* root){ vector<vector<int> > res; //记录每层的结点值 if(!root) return res; //如果根节点为空,返回空 queue<TreeNode*> q; //结点指针队列 q.push(root); //根指针入队 while(!q.empty()){ res.push_back(vector<int>()); //初始化res数组 for(int i=q.size(); i--; ){ //q.size是当前层的元素个数 root=q.front(); //root指向队头 q.pop(); //队头指针出队 res.back().push_back(root->val); //记录结点值 if(root->left) q.push(root->left); if(root->right) q.push(root->right); //下一层结点入队 } } return res; //返回结果 } };
// c int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes) { int** ans = (int**)malloc(sizeof(int*) * 2000); // 开辟返回数组空间,最大为2000 *returnColumnSizes = malloc(sizeof(int) * 2000); // *returnColumnSizes数组记录每一层节点的个数 *returnSize = 0; if (root == NULL) return ans; struct TreeNode* queue[2000]; // 模拟队列数组 int head = 0, tail = 0; // head、tail分别指向队列的头部和尾部 queue[tail++] = root; // 初始先将根节点入队 while (head != tail) { // 结束条件为队列为空,即tail==head int len = tail - head; // 头部到尾部的节点数即为当前层的全部节点 ans[*returnSize] = malloc(sizeof(int) * len); // 开辟当前层的一维数组空间 int start = head; head = tail; // start被赋值后变为当前层的头部,head被赋值后变为当前层的尾部 for (int i = start; i < head; i++) { ans[*returnSize][i - start] = queue[i]->val; //记录当前层的结点值 if (queue[i]->left) queue[tail++] = queue[i]->left; if (queue[i]->right) queue[tail++] = queue[i]->right; } (*returnColumnSizes)[(*returnSize)++] = len; // *returnColumnSizes赋值,并将层数加1 } return ans; }
//C++ 迭代版 class Solution { public: bool check(TreeNode *u, TreeNode *v) { queue <TreeNode*> q; q.push(u); q.push(v); //成对入队 while (!q.empty()) { u = q.front(); q.pop(); v = q.front(); q.pop(); //成对出队 if (!u && !v) continue; //均为空,则跳过 if ((!u || !v) || (u->val != v->val)) return false; q.push(u->left); q.push(v->right); //成对入队 q.push(u->right); q.push(v->left); //成对入队 } return true; //均对称,则返回true } bool isSymmetric(TreeNode* root) { return check(root->left, root->right); } };
//C 递归版 更优雅 bool check(struct TreeNode *p, struct TreeNode *q) { if (!p && !q) return true; if (!p || !q) return false; return p->val == q->val && check(p->left, q->right) && check(p->right, q->left); } bool isSymmetric(struct TreeNode* root) { return check(root->left, root->right); }
//C++ 递归版 class Solution { public: bool check(TreeNode *p, TreeNode *q) { if (!p && !q) return true; if (!p || !q) return false; return p->val==q->val && check(p->left, q->right) && check(p->right, q->left); } bool isSymmetric(TreeNode* root) { return check(root->left, root->right); } };
//c 类似先序遍历 int levels; void dfs(struct TreeNode* root, int level, int* counts, double* sums){ if (root == NULL) return; if (level < levels){ //若是同一层 sums[level] += root->val; counts[level] += 1; } else{ //开始下一层 sums[levels] = (double)root->val; counts[levels++] = 1; } dfs(root->left, level+1, counts, sums); dfs(root->right, level+1, counts, sums); } double* averageOfLevels(struct TreeNode* root, int* returnSize){ levels=0; //层数 int* counts = malloc(sizeof(int)*1001); //每层结点个数 double* sums = malloc(sizeof(double)*1001); //每层结点的数值和 double* averages = malloc(sizeof(double)*1001); //每层结点的平均值 dfs(root, 0, counts, sums); //递归搜索 *returnSize = levels; //层数 for(int i = 0; i < levels; i++){ averages[i] = sums[i]/counts[i]; } return averages; }
//c++ class Solution{ public: void dfs(TreeNode* root, int level, vector<int> &counts, vector<double> &sums){ if(root == nullptr) return; if(level < sums.size()){ sums[level] += root->val; counts[level] += 1; } else{ sums.push_back(1.0*root->val); counts.push_back(1); } dfs(root->left, level+1, counts, sums); dfs(root->right, level+1, counts, sums); } vector<double> averageOfLevels(TreeNode* root){ auto counts = vector<int>(); auto sums = vector<double>(); auto averages = vector<double>(); dfs(root, 0, counts, sums); for(int i = 0; i < sums.size(); i++){ averages.push_back(sums[i]/counts[i]); } return averages; } };
// 二叉树的 4 种遍历————静态链表(数组模拟) #include <stdio.h> #define MAXN 100 typedef struct { char data; int lchild; // 左孩子下标,-1代表NULL int rchild; // 右孩子下标,-1代表NULL } BiTNode; // 样例树: // A // B C // D ∅ E F BiTNode tree[MAXN] = { {'A', 1, 2}, {'B', 3, -1}, {'C', 4, 5}, {'D', -1, -1}, {'E', -1, -1}, {'F', -1, -1} }; // 先序:根 左 右 void PreOrder(int root) { if (root == -1) return; printf("%c ", tree[root].data); PreOrder(tree[root].lchild); PreOrder(tree[root].rchild); } // 中序:左 根 右 void InOrder(int root) { if (root == -1) return; InOrder(tree[root].lchild); printf("%c ", tree[root].data); InOrder(tree[root].rchild); } // 后序:左 右 根 void PostOrder(int root) { if (root == -1) return; PostOrder(tree[root].lchild); PostOrder(tree[root].rchild); printf("%c ", tree[root].data); } // 层序遍历 void LevelOrder(int root) { int queue[MAXN]; int front = 0, rear = 0; if(root == -1) return; queue[rear++] = root; while(front < rear) { int cur = queue[front++]; printf("%c ", tree[cur].data); if(tree[cur].lchild != -1) queue[rear++] = tree[cur].lchild; if(tree[cur].rchild != -1) queue[rear++] = tree[cur].rchild; } } int main() { int root = 0; //根节点下标0 printf("先序遍历:"); PreOrder(root); printf("\n"); printf("中序遍历:"); InOrder(root); printf("\n"); printf("后序遍历:"); PostOrder(root); printf("\n"); printf("层序遍历:"); LevelOrder(root); printf("\n"); return 0; }
。
浙公网安备 33010602011771号