以下代码可以正确地按层换行输出二叉树的节点值。
void printByLevel(TreeNode* root) { if (!root) return; queue<TreeNode*> q; q.push(root); while (!q.empty()) { for (int i = 0; i < q.size(); ++i) { TreeNode* cur = q.front(); q.pop(); cout << cur->val << " "; if (cur->left) q.push(cur->left); if (cur->right) q.push(cur->right); } cout << endl; }}