按层打印二叉树

题目描述

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

Code

#include <bits/stdc++.h>

using namespace std;

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) {
        vector<vector<int> > ans;
        queue<TreeNode* > Q;
        if(pRoot)
            Q.push(pRoot);
        int num = 1;
        int dept=0;
        while(!Q.empty()){
            int num1=0;
            vector<int >vc;
            for(int i=0;i<num;i++){
                TreeNode* tmp=Q.front();
                Q.pop();
                if(tmp->left)
                    Q.push(tmp->left),num1++;
                if(tmp->right)
                    Q.push(tmp->right),num1++;
                vc.push_back(tmp->val);
            }
            ans.push_back(vc);
            dept++;
            num=num1;
        }
        return ans;
    }
}f;

int main() {
    TreeNode f1=TreeNode(1);
    TreeNode f2=TreeNode(2);
    TreeNode f3=TreeNode(3);
    TreeNode f4=TreeNode(4);
    f1.left=&f2;
    f2.left=&f4;
    f1.right=&f3;
    TreeNode* root = &f1;
    vector<vector<int> > c = f.Print(root);
    for(int i=0;i<=2;i++){
        vector<int > tmp = c[i];
        for(int j=0;j<tmp.size();j++)
            printf("%d ",tmp[j]);
        puts("");
    }
    return 0;
}
### 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、付费专栏及课程。

余额充值