题目描述:
//利用队列 进行广度优先搜索
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> levelOrderBottom(TreeNode* root) { //广度优先搜索之后逆序输出 用队列 vector<vector<int> > ret; if(NULL == root) return ret; queue<TreeNode *> vi; vi.push(root); while(!vi.empty()){ vector<int> v; for(int i = 0, n = vi.size(); i < n ; i++ ){ TreeNode *tmp = vi.front(); vi.pop(); if(tmp->left != NULL) vi.push(tmp->left); if(tmp->right != NULL) vi.push(tmp->right); v.push_back(tmp->val); } ret.push_back(v); } reverse(ret.begin(),ret.end()); return ret; } };