題目詳情
給你一個二叉樹,請你返回其按 層序遍歷 得到的節點值。 (即逐層地,從左到右訪問所有節點)。
示例:
二叉樹:[3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回其層次遍歷結果:
[
[3],
[9,20],
[15,7]
]
——題目難度:中等
-使用寬搜的思路,用隊列和vector容器即可解決這題,下面代碼
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
if (root == NULL) return {};
vector<vector<int>> ans;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int count = q.size(); //count爲這一層的元素個數
vector<int> level; //level存儲這一層中的元素
while (count--) {
TreeNode* t = q.front(); //讀取隊首
level.push_back(t->val);
q.pop(); //出隊
if(t->left) q.push(t->left); //入隊
if(t->right) q.push(t->right); //入隊
}
ans.push_back(level);
}
return ans;
}
};
結果