思路比较简单,典型的宽度优先遍历,但是在使用vector的时候出现了些问题。先上ac代码:
vector> levelOrder(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function vector > result; if(root == NULL) return result; result.clear(); vector tmp; vector nodeVec; nodeVec.reserve(1000); nodeVec.push_back(root); vector ::iterator head = nodeVec.begin(), tail = nodeVec.end()-1; while(!nodeVec.empty()){ tmp.clear(); while(head <= tail){ tmp.push_back((*head)->val); if((*head)->left != NULL) nodeVec.push_back((*head)->left); if((*head)->right != NULL) nodeVec.push_back((*head)->right); head++; } result.push_back(tmp); nodeVec.erase(nodeVec.begin(), head); head = nodeVec.begin(); tail = nodeVec.end()-1; } return result; }
出现的问题需要从下面这小段代码说起:
vector v;// v.reserve(100); v.push_back(1); vector ::iterator i = v.begin(); cout<<*i<