二叉树层序遍历-C++

1.自上而下层序遍历输出,题目描述参见力扣102

#include 
#include 
#include 
using namespace std;

struct TreeNode {
	int val;
	TreeNode* left;
	TreeNode* right;
	TreeNode(): val(0),left(nullptr), right(nullptr) {}
	TreeNode(int data) : val(data), left(nullptr), right(nullptr) {}
};

vector> printTree(TreeNode* root) {
	if (root == nullptr) {
		return{};
	}
	vector> res;
	queue tool;
	tool.emplace(root);

	while (!tool.empty()) {
		vector tmp;
		int n = tool.size();

		while (n--) {
			tmp.emplace_back(tool.front()->val);
			if (tool.front()->left != nullptr) {
				tool.emplace(tool.front()->left);
			}
			if (tool.front()->right != nullptr) {
				tool.emplace(tool.front()->right);
			}
			tool.pop();
		}

		res.emplace_back(tmp);
	}

	return res;
}

int main() {
	TreeNode* root = new TreeNode(1);
	TreeNod

你可能感兴趣的:(算法题)