从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
开始打印任意一层前记录list大小,以区分各行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
class Solution { public: vector<vector<int> > Print(TreeNode* pRoot) { if (pRoot == nullptr) { return {}; } else { vector<vector<int>> result; list<TreeNode*> l{pRoot}; int size; while (size = l.size()) { vector<int> row; row.reserve(size); for (; size > 0; size--) { TreeNode *n = l.front(); l.pop_front(); row.push_back(n->val); if (n->left != nullptr) { l.push_back(n->left); } if (n->right != nullptr) { l.push_back(n->right); } } result.push_back(row); } return result; } } };
|