我的思路
vector<vector<int>> levelOrderBottom(TreeNode* root) {
queue<TreeNode*> s1,s2;
vector<vector<int>> vv;
//边际条件
if(root != NULL)
s1.push(root);
else return vv;
// 用s1,s2逐层遍历
while(1){
// s1 turn
vector<int> v;
while(!s1.empty()){
if(s1.front()->left != NULL)
s2.push(s1.front()->left);
if(s1.front()->right != NULL)
s2.push(s1.front()->right);
v.push_back(s1.front()->val);
s1.pop();
}
if(!v.empty())
vv.insert(vv.begin(),v);
//s2 turn
v.clear();
while(!s2.empty()){
if(s2.front()->left != NULL)
s1.push(s2.front()->left);
if(s2.front()->right != NULL)
s1.push(s2.front()->right);
v.push_back(s2.front()->val);
s2.pop();
}
if(!v.empty())
vv.insert(vv.begin(),v);
if(s1.empty()) break;
}
return vv;
}
更高效的思路
充分的利用了vector的方法,明显比我更了解vector size的应用
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> v;
traversal(v, root, 0);
reverse(v.begin(),v.end()); // 头尾交换
return v;
}
void traversal(vector<vector<int>> & v, TreeNode* node, int depth){
if(node){
traversal(v, node->left, depth+1);
traversal(v, node->right, depth+1);
if(depth + 1 >= v.size()){
v.resize(depth + 1); //这个resize和depth,把vector的下表运算用的6到不行
};
v[depth].push_back(node->val);
}
}
};