二叉树的层序遍历 改进版 Binary Tree Level Order Traversal II

题目:Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

思路:
由于题目要求输出结果中每一层的结点是分开的。所以需要再层序遍历的过程中加入一个标记,来区分当时是哪一层。所用的方法就是在根结点入队列之后就马上把一个NULL入队。当再次看到这个NULL的时候,说明该层结束了,这是马上再入一个NULL,表示新层的开始。当遇到NULL且此时队列已经为空的时候,说明所有节点遍历完毕。

代码:
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int> > levelOrderBottom(TreeNode *root) {
        vector<vector<int> > v;
        if(root == NULL)
            return v;
        vector<int> tmp;
        queue<TreeNode *> q;
        q.push(root);
        q.push(NULL);
        while(!q.empty())
        {
            TreeNode *k = q.front();
            q.pop();
            if(k == NULL)
            {
                if(!q.empty()) // 如果后面还有元素,就再一个NULL
                    q.push(NULL);
                v.push_back(tmp);
                tmp.clear();
                continue;
            }
            tmp.push_back(k->val);
            if(k->left != NULL)
                q.push(k->left);
            if(k->right != NULL)
                q.push(k->right);
        }
        reverse(v.begin(), v.end());
        return v;
    }
};



### C语言实现二叉树层序遍历 二叉树层序遍历是一种基于广度优先搜索(BFS)的方法,其核心在于利用队列来逐层访问节点。以下是完整的C语言代码实现: #### 定义二叉树节点结构 首先定义二叉树节点的数据结构 `BiTree`,它包含三个部分:当前节点值、指向左子树的指针以及指向右子树的指针。 ```c #include <stdio.h> #include <stdlib.h> typedef struct BiTNode { char data; struct BiTNode *lchild, *rchild; } BiTNode, *BiTree; // 创建新节点函数 BiTree CreateNode(char value) { BiTree newNode = (BiTree)malloc(sizeof(BiTNode)); newNode->data = value; newNode->lchild = NULL; newNode->rchild = NULL; return newNode; } ``` #### 队列操作辅助函数 为了支持层序遍历,需要引入一个队列来管理待处理的节点。这里通过数组模拟队列的操作。 ```c #define MAX_QUEUE_SIZE 100 typedef struct Queue { BiTree elements[MAX_QUEUE_SIZE]; int front, rear; } Queue; void InitQueue(Queue *q) { q->front = q->rear = 0; } int IsEmpty(Queue *q) { return q->front == q->rear; } int IsFull(Queue *q) { return (q->rear + 1) % MAX_QUEUE_SIZE == q->front; } void Enqueue(Queue *q, BiTree item) { if (!IsFull(q)) { q->elements[q->rear] = item; q->rear = (q->rear + 1) % MAX_QUEUE_SIZE; } } BiTree Dequeue(Queue *q) { if (!IsEmpty(q)) { BiTree temp = q->elements[q->front]; q->front = (q->front + 1) % MAX_QUEUE_SIZE; return temp; } return NULL; } ``` #### 层序遍历函数 最后编写层序遍历的核心逻辑。从根节点开始将其加入队列,随后依次取出队首节点并打印其值,再将它的左右孩子分别入队,直至队列为空为止。 ```c void LevelOrderTraversal(BiTree root) { if (root == NULL) return; Queue queue; InitQueue(&queue); Enqueue(&queue, root); while (!IsEmpty(&queue)) { BiTree current = Dequeue(&queue); printf("%c ", current->data); if (current->lchild != NULL) { Enqueue(&queue, current->lchild); } if (current->rchild != NULL) { Enqueue(&queue, current->rchild); } } } ``` 以上即为完整的二叉树层序遍历代码实现[^4]。 --- ### 示例运行程序 下面是一个简单的测试案例,展示如何构建一棵二叉树并对其实现层序遍历。 ```c int main() { // 构建如下所示的一棵二叉树: // A // / \ // B C // / \ / // D E F BiTree root = CreateNode('A'); root->lchild = CreateNode('B'); root->rchild = CreateNode('C'); root->lchild->lchild = CreateNode('D'); root->lchild->rchild = CreateNode('E'); root->rchild->lchild = CreateNode('F'); printf("Level Order Traversal of the Binary Tree is:\n"); LevelOrderTraversal(root); // 输出应为: A B C D E F return 0; } ``` 此代码片段展示了创建一颗小型二叉树的过程及其对应的层序遍历结果[^5]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值