看到和自己一样的思路,就先记下来,
我用的vector记录每一层的结点,结果内存爆了
用队列方便
原文链接
https://www.nowcoder.com/profile/6614408/codeBookDetail?submissionId=16362055
vector<vector<int> > Print(TreeNode* pRoot) { vector<vector<int>>res; if(pRoot == NULL) return res; queue<TreeNode *>que; que.push(pRoot); bool flog = false; while(!que.empty()) { vector<int>vec; const int size = que.size(); for(int i=0;i<size;i++) { TreeNode * tmp = que.front(); que.pop(); vec.push_back(tmp->val); if(tmp->left) que.push(tmp->left); if(tmp->right) que.push(tmp->right); } if(flog) std::reverse(vec.begin(),vec.end()); res.push_back(vec); flog = !flog; } return res; }