zoukankan      html  css  js  c++  java
  • 把二叉树打印成多行

    时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M

    题目描述

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

    思路:

    广度优先搜索,借助队列

    /*
    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>> res;
                if(!pRoot)
                    return res;
                queue<TreeNode*> que;
                que.push(pRoot);
                while(!que.empty())
                {
                    vector<int> vec;
                    int len = que.size();
                    for(int i =0;i < len;i++)
                    {
                        TreeNode *temp = que.front();
                        vec.push_back(temp->val);
                        que.pop();
                        if(temp->left) que.push(temp->left);
                        if(temp->right) que.push(temp->right);
                    }
                    res.push_back(vec);
                }
                return res;
            }
        
    };
    
  • 相关阅读:
    团队题目及相关介绍
    团队介绍
    寒假8
    寒假作业七
    寒假7
    寒假作业六
    寒假6
    寒假作业五
    寒假5
    寒假作四
  • 原文地址:https://www.cnblogs.com/whiteBear/p/12692850.html
Copyright © 2011-2022 走看看