2.3b 二叉树的层序遍历

2.3b 二叉树的层序遍历_哔哩哔哩_bilibili

 

// 二叉树的层序遍历(使用链式队列)
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>

//定义二叉树的结点
typedef struct BiTNode{
    char data; //结点数据
    struct BiTNode *lchild; //左孩子指针
    struct BiTNode *rchild; //右孩子指针
}BiTNode;

//定义队列的结点
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 main(){
    //插入root
    BiTNode *root=(BiTNode*)malloc(sizeof(BiTNode));
    root->data='A';

    //插入lchild
    BiTNode *p=(BiTNode*)malloc(sizeof(BiTNode));
    p->data='B';
    root->lchild=p;
    
    //插入rchild
    p=(BiTNode*)malloc(sizeof(BiTNode));
    p->data='C';
    root->rchild=p;

    LevelOrder(root); //层序遍历
    return 0;
}

 

 

102. 二叉树的层序遍历 - 力扣(LeetCode)

//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;
}

 

101. 对称二叉树 - 力扣(LeetCode)

//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);
    }
};

 

637. 二叉树的层平均值 - 力扣(LeetCode)

//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;
    }
};

 

posted @ 2026-09-25 07:02  董晓  阅读(0)  评论(0)    收藏  举报