102. Binary Tree Level Order Traversal

我解決這道題用的是一個雙端隊列配合,按照層次把節點push到隊列中,先把該節點的值存入到vector中,然後在該隊列中移除該節點。當一層結束後,開始判斷該層每個節點的左右子樹,push到隊列中,重新循環。class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
queue<TreeNode*> tree;
if(root == NULL)
return res;
tree.push(root);
while(!tree.empty())
{
vector<int> temp;
int size = tree.size();
for(int i=0; i < size; i++)
{
TreeNode* t = tree.front();
tree.pop();
temp.push_back(t->val);
if(t->left)
tree.push(t->left);
if(t->right)
tree.push(t->right);
}
res.push_back(temp);
}
return res;
}
};

發佈了50 篇原創文章 · 獲贊 7 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章