和上一道题思路差不多,只是这次插入数字的方向需要换一下。
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 47 48
|
class Solution { public: vector<vector<int> > Print(TreeNode* pRoot) { vector<vector<int>> result; if(pRoot==NULL) return result; queue<TreeNode*> q; q.push(pRoot); int now=1,next=0,layer=0; vector<int>* v=new vector<int>(); while(!q.empty()){ TreeNode* t=q.front(); q.pop(); now--; if(layer%2==0){ v->push_back(t->val); }else{ v->insert(v->begin(),t->val); } if(t->left!=NULL) { q.push(t->left); next++; } if(t->right!=NULL) { q.push(t->right); next++; } if(now==0){ now=next; next=0; layer++; result.push_back(*v); v=new vector<int>(); } } return result; }
};
|