《剑指Offer》43. 把二叉树打印成多行

题目:43. 把二叉树打印成多行

知识点:二叉树

题目描述:

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

解题思路:

主要是使用 BFS ,通过使用队列来对节点进行保存,保证节点的先进先出,同时对每一层的入列和出列的节点进行计数,以此判断每一层的结束位置。

代码:

//解法一(自研):
    vector<vector<int>> Print(TreeNode* pRoot) {
        vector<vector<int>> res;
        if(pRoot == nullptr) return res;
        vector<int> array;
        queue<TreeNode*> s;
        s.push(pRoot);
        int count = 1;
        
        while(!s.empty()){
            
            while(count-- > 0){
                TreeNode* node = s.front();
                s.pop();
                if(node->left != nullptr) s.push(node->left);
                if(node->right != nullptr) s.push(node->right);
                array.push_back(node->val);
            }
            res.push_back(array);
            array.clear();
            count = s.size();
        }
        
        return res;
    }


//解法二(剑指Offer 思路同上):
void Print(BinaryTreeNode* pRoot)
{
    if(pRoot == nullptr)
        return;

    std::queue<BinaryTreeNode*> nodes;
    nodes.push(pRoot);
    int nextLevel = 0;
    int toBePrinted = 1;
    while(!nodes.empty())
    {
        BinaryTreeNode* pNode = nodes.front();
        printf("%d ", pNode->m_nValue);

        if(pNode->m_pLeft != nullptr)
        {
            nodes.push(pNode->m_pLeft);
            ++nextLevel;
        }
        if(pNode->m_pRight != nullptr)
        {
            nodes.push(pNode->m_pRight);
            ++nextLevel;
        }

        nodes.pop();
        --toBePrinted;
        if(toBePrinted == 0)
        {
            printf("\n");
            toBePrinted = nextLevel;
            nextLevel = 0;
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值