1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 11 static int wing=[]() 12 { 13 std::ios::sync_with_stdio(false); 14 cin.tie(NULL); 15 return 0; 16 }(); 17 18 class Solution 19 { 20 public: 21 vector<vector<int>> levelOrderBottom(TreeNode* root) 22 { 23 queue<TreeNode*> q; 24 vector<vector<int>> vvint; 25 vector<int> vint; 26 if(root==NULL) 27 return vvint; 28 q.push(root); 29 while(!q.empty()) 30 { 31 for(int i=0,n=q.size();i<n;i++) 32 { 33 34 TreeNode* p=q.front(); 35 q.pop(); 36 vint.push_back(p->val); 37 if(p->left!=NULL) 38 q.push(p->left); 39 if(p->right!=NULL) 40 q.push(p->right); 41 } 42 vvint.push_back(vint); 43 vint.clear(); 44 } 45 reverse(vvint.begin(),vvint.end()); 46 vector<vector<int>> &res=vvint; 47 return res; 48 } 49 };
用层次遍历,把每个元素放入vector里面,扫完一层就把vector放入vvint,扫描完整个树之后,将vvint逆置返回即可。这里最好返回引用。
浙公网安备 33010602011771号