按层打印二叉树

本文介绍了一种二叉树的遍历方法——按层遍历,并详细讲解了其实现过程。通过队列实现对二叉树节点的逐层访问,最后返回一个二维数组,表示每一层的节点数据。

二叉树是一种常见的数据结构,由n(你>=0)个节点构成,每个节点最多有两个子二叉树。
由二叉树的定义可知,一棵二叉树由三部分组成:根节点、左子树和右子树。二叉树的遍历方式有先序遍历、中序遍历和后序遍历。
这里写图片描述
先序遍历:首先访问根节点,然后访问根节点左孩子,再访问根节点的右孩子。

中序遍历:首先访问根节点左孩子,然后访问根节点,在访问根节点的右孩子。

后序遍历:首先访问根节点左孩子,然后访问根节点的右孩子,再访问根节点。

上述三种遍历方式原理相同,可以采用递归的方式实现遍历。

这里要说的是二叉树的另一种遍历方法:按层遍历。

按层遍历即从二叉树的根节点开始从上至下从左至右依次访问节点。
在介绍按层遍历的实现前先定义一下二叉树的结构。

class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}

上述代码即定义了二叉树中每个节点的结构。节点的数据 val、该节点的左孩子 left和该节点的有孩子right。

下面以一个实例问题实现二叉树的按层遍历。
按层遍历算法如下:
1、初始化设置一个队列;
2、把根节点先入队列;
3、当队列非空时:
①、出队列取得当前队头结点,访问该节点;
②、若该结点的左孩子结点非空,则将该结点的左孩子结点放入队列。
③、若该结点的右孩子结点非空,则将该结点的右孩子结点放入队列。
4、结束

问题
给定二叉树的根结点root,请返回打印结果,结果按照每一层一个数组进行储存,所有数组的顺序按照层数从上往下,且每一层的数组内元素按照从左往右排列。


/**
     * 二叉树的按层遍历
     * 
     * @param root
     *            二叉树的根节点
     * @return 返回一个二维数组表示每一层由哪些数据构成
     */
    public static int[][] printTree(TreeNode root) {
        // 如果二叉树为空立即结束
        if (root == null) {
            return null;
        }

        // 作用1:存储每一层的数据集合
        // 作用2:转化为数组返回
        ArrayList<ArrayList<Integer>> array = new ArrayList<>();
        // 临时存放每层结点
        ArrayList<Integer> temp;
        int last = 0;
        int nlast = 0;
        // 当前结点
        TreeNode curr;
        Queue<TreeNode> queue = new LinkedList<>();
        // 步骤1 :根节点入队列
        curr = root;
        queue.offer(curr);
        nlast = curr.val;
        last = nlast;
        temp = new ArrayList<>();
        // 步骤二 : 循环遍历二叉树
        while (!queue.isEmpty()) {
            curr = queue.poll();
            temp.add(curr.val);
            // 左孩子非空,将左孩子如队列
            if (curr.left != null) {
                queue.offer(curr.left);
                nlast = curr.left.val;
            }
            // 右孩子非空,将右孩子入队列
            if (curr.right != null) {
                queue.offer(curr.right);
                nlast = curr.right.val;
            }
            if (curr.val == last) {
                last = nlast;
                array.add(temp);
                temp = new ArrayList<>();
            }
        }
        // 将array中的结点数据转换为二维数组返回
        int[][] result = new int[array.size()][];
        for (int i = 0; i < result.length; i++) {
            ArrayList<Integer> tempArray = array.get(i);
            result[i] = new int[tempArray.size()];
            int n = result[i].length;
            for (int j = 0; j < n; j++) {
                result[i][j] = tempArray.get(j);
            }
        }
        return result;
    }
### 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、付费专栏及课程。

余额充值