震惊,竟然直接就把medium敲出来了
感觉不难,就是bfs使用队列,利用oldnum记录本层元素个数,newnum记录下一层元素个数
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
if(!root)
return result;
queue<TreeNode*> quOfTree;
quOfTree.push(root);
vector<int> value;
unsigned oldNum=1;
unsigned newNum=0;
while(oldNum){
TreeNode*pT=quOfTree.front();
quOfTree.pop();
if(pT->left){
quOfTree.push(pT->left);
++newNum;
}
if(pT->right){
quOfTree.push(pT->right);
++newNum;
}
value.push_back(pT->val);
if(--oldNum==0){
oldNum=newNum;
newNum=0;
result.push_back(value);
value.erase(value.begin(),value.end());
}
}
return result;
}
};