【剣指offer】面接問題32-III.二叉木IIIを上から下まで印刷


2020.7.9更新
#include
#include
#include
#include
using namespace std;
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> ans;
        if (root == nullptr) return ans;
        queue<TreeNode*> q;
        q.push(root);
        int layer = 0;
        while (!q.empty()) {
            vector<int> temp;
            int len = q.size();
            for (int i = 0; i < len; i++) {
                TreeNode* front = q.front();
                temp.push_back(front->val);
                q.pop();
                if (front->left != nullptr) q.push(front->left);
                if (front->right != nullptr) q.push(front->right);
            }
            if (layer & 1 != 0) {
                reverse(temp.begin(), temp.end());//algorithm     
            }
            ans.push_back(temp);
            layer++;
        }
        return ans;
    }
};

問題を解く構想.
BFSは偶数層に対して遍歴し,reverseは奇数層に対してreverseを行い,reverse用法参考文は行わない
コード#コード#
class Solution {
public:
	vector<vector<int>> levelOrder(TreeNode* root) {
		vector<vector<int>> res;
		if (root!=NULL)
		{
			bool flag = true;//    false,    true
			queue<TreeNode*> q;
			q.push(root);
			while (!q.empty())
			{
				vector<int> temp;
				int qSize = q.size();
				flag = !flag;
				for (int i=0;i<qSize;i++)
				{
					
					TreeNode* front = q.front();
					temp.push_back(front->val);
					q.pop();
					if (front->left != NULL) q.push(front->left);
					if (front->right != NULL) q.push(front->right);
				}
				if (flag)
				{
					reverse(temp.begin(), temp.end());
				}
				res.push_back(temp);
			}
		}
		return res;
	}
};