总结:
1. 注意 cnt-- 的位置以及 level push 的位置
2. II 在 1 的基础上加个 stack 或者直接 reverse 都可以
代码:
class Solution {public: vector> levelOrder(TreeNode *root) { vector > res; if(root == NULL) return res; queue record; vector level; int cnt = 1, nextcnt = 0; record.push(root); while(!record.empty()) { TreeNode * tn = record.front(); record.pop(); level.push_back(tn->val); if(tn->left) { record.push(tn->left); nextcnt += 1; } if(tn->right) { record.push(tn->right); nextcnt += 1; } cnt --; if(cnt == 0) { cnt = nextcnt; nextcnt = 0; // push_back res.push_back(level); level.clear(); } } return res; }};