1、从上往下打印出二叉树的每个节点,同层节点从左至右打印

本文介绍了如何从上往下,同层从左至右打印二叉树的节点。通过使用队列,先将根节点入队,然后循环遍历队列,每次取出节点并访问其左右子节点,依次加入队列,直至队列为空,实现层次遍历。

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

问题描述:传入根节点,从上往下打印出二叉树的每个节点,同层节点从左至右打印。

解决思路:使用一个队列存放节点。先将根节点加入到队列中,然后循环遍历队列中的元素,遍历过程中,访问该节点的左右子节点,再将左右子节点加入到队列中。

public class Solution {   
    public ArrayList<TreeNode> PrintFromTopToBottom(TreeNode root) {   
        //创建一个列表用来存储节点  
        ArrayList<TreeNode> treeList=new ArrayList<TreeNode>();   
        if(root==null){//没有节点   
             return null;   
         }   
        //1、先存入根节点  
        treeList.add(root);  
       //2、循环遍历列表,一开始列表中只有根节点,因此size==1   
       for(int i=0;i<treeList.size();i++){   
            TreeNode node=  treeList.get(i);   
       	    //3、如果左子节点不为空,则将左子节点加入到列表中,这时列表的size加1  
            if(node.left!=null){   
                treeList.add(node.left);   
             }   
              //3、如果右子节点不为空,则将右子节点加入到列表中,这时列表的size加1  
             if(node.right!=null){
 		treeList.add(node.right);
 	      }
		//4、因为执行上面操作后会增加列表的size,因此可以继续循环下一个节点,直到循环完所有节点 
		} 
	return treeList;
	 }
 }

如图所示二叉树:


1、首先将根节点加入到list中,因此此时list中数据为:  

1    

2、循环遍历列表:list.size = 1,i=0时获取到节点1,因为节点1有左子节点2,因此将左子节点2加入到list中,此时list.size = 2

12   

3、因为节点1有右子节点3,因此将右子节点3加入到list中,此时list.size=3

123  

4、因为list.size=3,因此可以进行下一次循环,i=1,获取到节点2,因为节点2有左子节点4,因此将左子节点4加入到list中,此时list.size=4

1234 

5、因为节点2有子右节点5,因此将右子节点5加入到list中,此时list.size=5

12345

6、继续循环遍历list,i=2,获取到节点3,因为节点3没有子节点,因此继续循环遍历list,因为节点45均没有子节点,因此遍历完成。


### 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. } } ``` 上述代码片段展示了完整的解决方案框架,其中涉及到了创建新实例化对象时所需的内存分配细节等内容并未给具体实现方式,实际应用中还需要补充这部分缺失的功能模块才能构成可执行程序文件。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值