按层打印二叉树

本文介绍了一种从上到下按层打印二叉树的方法,确保同一层节点从左至右输出,并详细阐述了使用队列实现该过程的具体算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

用last记录上一层最后一个
用nlast记录下一层最后一个;
当打印到last的时候,令last=nlast,保存一层即可。

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
        vector<vector<int> > Print(TreeNode* pRoot) {
            if(pRoot==NULL)
                return vector<vector<int>>{};
            vector<vector<int> > res;
            vector<int> vec;
            queue<TreeNode*> que;
            que.push(pRoot);
            TreeNode* last=pRoot;
            TreeNode* nlast=pRoot;

            while(!que.empty())
                {
                TreeNode* temp=que.front();
                que.pop();
                if(temp->left){
                    que.push(temp->left);
                    nlast=temp->left;
                }
                if(temp->right){
                    que.push(temp->right);
                    nlast=temp->right;               
                }
                vec.push_back(temp->val);
                if(temp==last)
                    {
                    res.push_back(vec);
                    last=nlast;
                    vec.clear();
                }

            }
                return res;
        }

};
### C语言实现按遍历二叉树并分行输出节点值 为了实现这一功能,可以采用广度优先搜索的方法来逐访问二叉树中的每一个节点,并利用队列结构保存待处理的子节点。下面展示了一个具体的例子。 #### 定义二叉树节点结构体以及辅助函数 首先定义`TreeNode`结构体表示二叉树的一个节点,它包含整数值`val`、指向左孩子和右孩子的指针成员变量;接着声明几个操作队列的基础方法,比如入队(`QueuePush`)、出队(`QueuePop`)等[^2]: ```c #include <stdio.h> #include <stdlib.h> // Define the structure of a binary tree node. typedef struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; } TreeNode; // Function prototypes for queue operations (to be implemented separately). void QueuePush(Queue*, TreeNode*); TreeNode* QueuePop(Queue*); ``` #### 次遍历逻辑 接下来编写核心算法部分——次遍历函数,在每次迭代过程中先获取当前有多少个元素(即队列长度),再依次取出这些元素打印其值并将它们的孩子加入到队尾等待下一轮处理直到整个树被完全遍历完毕为止。特别地,每当完成一的操作之后会额外输出换行符以便区分不同数的数据项: ```c /// @brief Level order traversal function that prints each level on new line. /// /// This function performs breadth-first search using an auxiliary queue to store nodes at current depth, /// printing their values and pushing children into the queue until all levels are processed. void printLevelOrder(TreeNode *root) { if (!root) return; // Handle empty tree case. Queue q = createQueue(); // Initialize queue with root element. enqueue(&q, root); while (!isEmpty(q)) { int count = getSize(q); // Record number of elements in this layer before processing starts. // Process all items currently present within the queue which represent one single horizontal row/level inside our BST. while (count--) { TreeNode *node = dequeue(&q); printf("%d ", node->val); // Add child nodes from both sides only when they exist so as not to introduce null pointers later down the road during iteration over next rows/layers. if (node->left != NULL) enqueue(&q, node->left); if (node->right != NULL) enqueue(&q, node->right); } putchar('\n'); // Move onto subsequent lines after finishing off every individual tier's worth of entries. } } ``` 上述代码片段展示了完整的解决方案框架,其中涉及到了创建新实例化对象时所需的内存分配细节等内容并未给出具体实现方式,实际应用中还需要补充这部分缺失的功能模块才能构成可执行程序文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值