剑指offer32.1 不分行从上往下打印二叉树

本文介绍了一种从上往下,按层从左至右打印二叉树结点的方法。通过使用队列进行层次遍历,可以有效地访问并打印出二叉树的所有结点。文章提供了C++和Python的实现代码。

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

剑指offer32.1 不分行从上往下打印二叉树

    从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序打印。

样例

输入如下图所示二叉树[8, 12, 2, null, null, 6, null, 4, null, null, null]
    8
   / \
  12  2
     /
    6
   /
  4

输出:[8, 12, 2, 6, 4]

思路

    用一个队列存放树节点,层次遍历访问所有结点,并且保存其数值。

AcWing-43 C++ code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> printFromTopToBottom(TreeNode* root) {
        if(root == NULL){
            return {};
        }
        queue<TreeNode* > q_node;
        vector<int> res;
        q_node.push(root);
        res.push_back(root->val);
        while(!q_node.empty()){
            if(q_node.front()->left){
                res.push_back(q_node.front()->left->val);
                q_node.push(q_node.front()->left);
            }
            if(q_node.front()->right){
                res.push_back(q_node.front()->right->val);
                q_node.push(q_node.front()->right);
            }
            q_node.pop();
        }
        return res;
    }
};

AcWing-43 python code:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def printFromTopToBottom(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if root == None:
            return []
        s_queue = []
        res = []
        s_queue.append(root)
        res.append(root.val)
        while len(s_queue):
            if s_queue[0].left:
                res.append(s_queue[0].left.val)
                s_queue.append(s_queue[0].left)
            if s_queue[0].right:
                res.append(s_queue[0].right.val)
                s_queue.append(s_queue[0].right)
            
            s_queue.remove(s_queue[0])
        return res        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值