60.把二叉树打印成多行

题目描述

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


思路一:

利用层次遍历二叉树的方式,用一个队列进行辅助,每次打印前取n = q.size(),可以保证逐行打印。


代码一:

/*
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 == NULL) return res;
            queue<TreeNode*> q;
            q.push(pRoot);
            vector<int> raw;
            TreeNode* tmpNode;
            while(!q.empty()) {
                int n = q.size();
                for(int i = 0; i < n; ++i) {
                    tmpNode = q.front();
                    q.pop();
                    raw.push_back(tmpNode->val);
                    if(tmpNode->left) q.push(tmpNode->left);
                    if(tmpNode->right) q.push(tmpNode->right);
                }
                res.push_back(raw);
                raw.clear();
            }
            return res;
        }
    
};

思路二:

与前一题的思路相同,上一题采用两个辅助栈,这一题可以采用两个辅助队列,每次队列入队都是先左孩子结点后右孩子结点,即可保证树的层次遍历输出。


代码二:

/*
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 == NULL) return res;
            queue<TreeNode*> q[2];
            q[0].push(pRoot);
            int cur = 0;
            int next = 1;
            TreeNode* tmpNode;
            vector<int> raw;
            while(!q[0].empty() || !q[1].empty()) {
                while(!q[cur].empty()) {
                    tmpNode = q[cur].front();
                    q[cur].pop();
                    raw.push_back(tmpNode->val);
                    if(tmpNode->left) q[next].push(tmpNode->left);
                    if(tmpNode->right) q[next].push(tmpNode->right);
                }
                res.push_back(raw);
                raw.clear();
                cur = 1 - cur;
                next = 1 - next;
            }
            return res;
        }
    
};

猜你喜欢

转载自blog.csdn.net/nichchen/article/details/80578207