剑指Offer:60-把二叉树打印成多行

题目描述

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

思路

实现

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    vector > Print(TreeNode* pRoot) {
        vector> res;
        if(!pRoot)
            return res;
        queue q;
        q.push(pRoot);
        while(!q.empty())
        {
            int len = q.size();
            vector tmp;
            for(int i = 0; i < len; i++)
            {
                TreeNode* root = q.front();
                q.pop();
                tmp.push_back(root->val);
                if(root->left)    q.push(root->left);
                if(root->right)    q.push(root->right);
            }
            res.push_back(tmp);
        }
        return res;
    }
};

你可能感兴趣的:(剑指Offer:60-把二叉树打印成多行)